<?php
/**
 * redis 缓存
 * zhouliang
 * 2020.09.04
 */

namespace App\Services\Tools;

use App\Enums\RoomEnum;
use App\Enums\UserEnum;
use App\Exceptions\BasicException;
use App\Jobs\QiPao\GeneralRoomJob;
use App\Models\MainDB\BlindDate\DatingUser;
use App\Models\MainDB\TitleGift\UserTitleGift;
use App\Models\MainDB\UserData;
use App\Repositories\Dynamic\DynamicBrowseRepository;
use App\Repositories\Dynamic\DynamicFollowRepository;
use App\Repositories\Dynamic\DynamicLikeRepository;
use App\Repositories\Group\GroupMemberRepository;
use App\Repositories\Group\GroupMessageRepository;
use App\Repositories\Group\GroupRepository;
use App\Repositories\LogRepository;
use App\Repositories\UserRepository;
use Carbon\Carbon;
use App\Enums\RedisKeyEnum;
use Illuminate\Support\Facades\Log;

class RedisService
{
    const KEY_ALL_CONFIG = 'DB_CONFIG_DATA';
    const KEY_HEAD_PICTURE = 'u:hp:';
    const KEY_ROOM_CHAT = 'room:chat:close';

    const ROOM_MAX_EXPIRE_TIME = 86400;

    public static function getConfig()
    {
        return app('redis')->get(self::KEY_ALL_CONFIG);
    }

    public static function setConfig($config)
    {
        app('redis')->set(self::KEY_ALL_CONFIG, $config);
    }


    // 金币存一下 redis

    /**
     * 存数据
     * @param $user_id
     * @param $data
     * @param $coin
     * @param $automatic
     * @param int $type
     * @return bool
     */


    public static function getSaveStrikeMoney($user_id, $data, $coin, $automatic, $type = 1)
    {
        $redis = app('redis')->connection('game2');
        $key = 'rebate:user:' . $user_id;
        // 使用哈希
        if ($redis->exists($key)) {
            if ($type == 2) {
                $redis->hset($key, 'automatic', $automatic);
                return true;
            } else {
                $redis->hincrby($key, 'balance', $coin);
            }
        } else {
            try {
                $redis->multi();
                $redis->hset($key, 'balance', $data['balance'] == 0 ? $coin : $data['balance'] + $coin);
                $redis->hset($key, 'input', isset($data['input']) ? $data['input'] : 0);
                $redis->hset($key, 'output', isset($data['output']) ? $data['input'] : 0);
                $automatic = $type == 2 ? 1 : 0;
                $redis->hset($key, 'automatic', $automatic);
                $redis->hset($key, 'user_id', $user_id);
                $redis->hset($key, 'output_919', 0);
                $redis->hset($key, 'input_919', 0);
                $redis->hset($key, 'compensate_919', 0);
                $redis->hset($key, 'output_895', 0);
                $redis->hset($key, 'input_895', 0);
                $redis->hset($key, 'compensate_895', 0);
                $redis->hset($key, 'output_910', 0);
                $redis->hset($key, 'input_910', 0);
                $redis->hset($key, 'compensate_910', 0);
                $redis->hset($key, 'to_count', isset($data['to_count']) ? $data['to_count'] : 0);
                $redis->exec();
            } catch (\Throwable $e) {

                return false;
            }

        }
        return true;
    }

    /**
     * @param $user_id
     * @return mixed|string|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public static function giveCheckAuth($user_id)
    {
        $key = "u:exp:" . $user_id;
        if (app('redis')->exists($key)) {
            return app('redis')->get($key);
        }
        return '0';
    }

    /**
     * @param $roomId
     * @return bool
     * 获取相亲房房间
     */
    public static function getDatingRoomList($roomId)
    {
        $Key = 'room:dating:list';
        if (!app('redis')->exists($Key)) {
            return false;
        }
        $list = app('redis')->lrange($Key, 0, -1) ?? [];
        return in_array($roomId, $list) ? true : false;
    }

    /**
     * @param $dating_id
     * @param $roomId
     * @param $sex
     * @param $score
     * @param $pit_number
     * 相亲房的头像
     * @return
     */
    public static function getDatingMemberAvatar($dating_id, $roomId, $sex, $score, $gift_user)
    {
        $Key = 'room:dating:avatar:' . $dating_id . ':' . $roomId . '_' . $sex . '_value';
        // 获取最高数的成员  1_0  100   1 是麦位 0 是 帽子等级  100 是值
        $redis = app('redis');
        $member = $gift_user;
        if ($redis->exists($Key)) {
            $redis->zIncrBy($Key, $score, $member);
        } else {
            $redis->zAdd($Key, [$member => $score]);
        }
        // 获取当前 男女的最高的帽子 麦位
        return $redis->zrevrange($Key, 0, 0, ['withscores' => true]) ?? [];
    }

    public static function getDatingMemberSceneMax($dating_id, $roomId)
    {
        $key_new = "room:dating:selectnew" . $roomId . '_' . $dating_id;
        $redis = app('redis');
        $info = $redis->lrange($key_new, 0, -1);
        if (empty($info)) {
            return 0;
        }
        $Scene_arr = [];
        $info = array_unique($info);
//        Log::info('info：' . json_encode($info));
        foreach ($info as $val) {
            $val_info = explode('_', $val);
            $Key_mall = 'room:dating:avatar:' . $dating_id . ':' . $roomId . '_' . 1 . '_value';
            $Key_girl = 'room:dating:avatar:' . $dating_id . ':' . $roomId . '_' . 2 . '_value';
            $mall = $redis->zscore($Key_mall, $val_info[0]);
            $girl = $redis->zscore($Key_girl, $val_info[1]);
            $Scene = $mall + $girl;
            $Scene_arr[] = $Scene;
        }
//        Log::info('Scene_arr：' . json_encode($Scene_arr));
        $Scene = max($Scene_arr) ?? 0;
        $key = 'room:dating:scene';
        $smallerScore = $redis->zrangebyscore($key, '-inf', ($Scene - 1), ['withscores' => true, 'limit' => [0, 100]]) ?? [];
        $rate = 0;
//        Log::info('smallerScore：' . json_encode($smallerScore));
        if ($smallerScore) {
//            $rate = key($smallerScore);
//            $smallerScore_count = count($smallerScore);
//            $rate = $smallerScore[$smallerScore_count - 1]; // 获取分数值
            $maxValue = max($smallerScore);
            $rate = array_keys($smallerScore, $maxValue)[0];
        }
        return $rate;
    }

    /**
     * @param $dating_id
     * @param $roomId
     * @param $sex
     * @param $score
     * @param $gift_user
     * @return array
     * 获取当前的用户 帽子 是否变动
     */
    public static function getDatingMemberAvatarMax($dating_id, $roomId, $sex, $score, $gift_user)
    {
        $Key = 'room:dating:avatar';
        $grade_Key = 'room:dating:avatar:' . $dating_id . ':' . $roomId . '_' . $sex . '_grade';
        $redis = app('redis');
        $smallerScore = $redis->zrangebyscore($Key, '-inf', ($score - 1), ['withscores' => true, 'limit' => [0, 100]]) ?? [];
        // 分数最高的 用户 是覅最高的 是的
//        print_r($smallerScore);
        $rate = 0;
        $is_rate = false;
        if ($smallerScore) {
            // 去数组第一键值
//            $rate = reset($smallerScore);
            //   $rate = key($smallerScore);
            $maxValue = max($smallerScore);
            $rate = array_keys($smallerScore, $maxValue)[0];
        }
        if ($redis->exists($Key)) {
//            $redis->zAdd($grade_Key, [$gift_user => $rate]);
//        } else {
//            // 获取 是否一样
            $rate_pit = $redis->zscore($grade_Key, $gift_user) ?? 0;
            if ($rate != $rate_pit) {
                $is_rate = true;
                $redis->zAdd($grade_Key, [$gift_user => $rate]);
            }
        }
        return [
            'is_o' => $is_rate,
            'rate' => $rate
        ];
    }

    public static function getDatingMemberAvatarMaxNew($dating_id, $roomId, $sex, $gift_user)
    {
        $Key = 'room:dating:avatar';
        $grade_Key = 'room:dating:avatar:' . $dating_id . ':' . $roomId . '_' . $sex . '_grade';
        $Key_girl = 'room:dating:avatar:' . $dating_id . ':' . $roomId . '_' . $sex . '_value';
        $redis = app('redis');
        // 获取当前用户的分数
        $rate = 0;


        // 获取 是否一样
        $score = $redis->zscore($Key_girl, $gift_user) ?? 0;
        $smallerScore = $redis->zrangebyscore($Key, '-inf', ($score - 1), ['withscores' => true, 'limit' => [0, 100]]) ?? [];
        if ($smallerScore) {
            // 去数组第一键值
            $maxValue = max($smallerScore);
            $rate = array_keys($smallerScore, $maxValue)[0];
        }
        $rate_pit = $redis->zscore($grade_Key, $gift_user) ?? 0;
        if ($rate != $rate_pit) {
            $redis->zAdd($grade_Key, [$gift_user => $rate]);
        }

        return true;
    }


//    /**
//     * @param $dating_id
//     * @param $roomId
//     * @param $user_id
//     * @param $sex
//     * @param $id
//     * @return bool
//     * 相亲房的头像
//     */
//    public static function getDatingMemberAvatar($dating_id, $roomId, $user_id, $sex, $id)
//    {
//        $Key = 'room:dating:avatar:' . $dating_id . '_' . $roomId . '_' . $sex;
//        // 获取最高数的成员
////        app('redis')->zrevrange($Key, 0, 0);
////        if (!app('redis')->exists($Key)) {
////            app('redis')->zadd($Key,
////                [$user_id => $id]
////            );
////            return true;
////        }
//        // 新增成员和给成员重新赋值
//        app('redis')->zadd($Key,
//            [$user_id => $id]
//        );
//        return true;
//    }

    /**
     * @param $roomId
     * 获取是否为相亲的房间  和流水线
     * @return int|\Laravel\Lumen\Application|mixed|void
     */
    public static function getDatingMember($dating_id, $roomId, $user_id, $total_price, $sex)
    {
        $Key = 'room:dating:score:' . $dating_id . '_' . $roomId . '_' . $sex;
        if (!app('redis')->exists($Key)) {
            app('redis')->zadd($Key,
                [$user_id => $total_price]
            );
            return $total_price;
        }
        $score = app('redis')->zscore($Key, $user_id);
        if ($score !== null) {
            app('redis')->zincrby($Key, $total_price, $user_id);
            return $score + $total_price;
        }
        // 添加成员
        app('redis')->zadd($Key,
            [$user_id => $total_price]
        );
        return $total_price;

// 获取成员的分数
//        $score = Redis::zscore($key, $member);
        //  新增后获取成员分数  获取成员的分数
//        Redis::zincrby($sortedSet, $score, $member);
        // 判断成员是否存在
//        $score = Redis::zscore('myzset', $member);
    }

    /**
     * @param $roomId
     * 获取是否为相亲的房间  和流水线
     * @return int|\Laravel\Lumen\Application|mixed|void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public static function getDating($roomId)
    {
        $Key = 'room:dating:' . $roomId;
        if (!app('redis')->exists($Key)) {
            return 0;
        }
        return app('redis')->get($Key);
    }

    public static function getAllOnPitUserId($roomId)
    {
        $roomAllKey = 'room:all:pit:' . $roomId;
        if (!app('redis')->exists($roomAllKey)) {
            return [];
        }
        $res = app('redis')->hGetAll($roomAllKey);
        $user_head_picture = [];
        foreach ($res as $k => $v) {
            $data = json_decode($v, true);
            if (empty($data) || $data['user_id'] == 0) {
                continue;
            }
            // 获取用户头像
            //  $user_head_picture[] = RedisService::getUserBaseInfo($data['user_id'], 'head_picture');
            $head_picture = RedisService::getUserBaseInfo($data['user_id'], 'head_picture');
            ($k == 9) ? array_unshift($user_head_picture, $head_picture) : $user_head_picture[] = $head_picture;
        }
        return $user_head_picture;
    }

    public static function getOnPitUserId($roomId, $pit_number = 0)
    {
        $roomAllKey = 'room:all:pit:' . $roomId;
        if (!app('redis')->exists($roomAllKey)) {
            return [];
        }
        $data = app('redis')->hGetAll($roomAllKey);
        $user_ids = [];
        foreach ($data as $v) {
            $v = json_decode($v, true);
            if (!empty($v['user_id'])) {
                $user_ids[$v['pit_number']] = $v['user_id'];
            }
        }
        if (empty($pit_number)) {
            return $user_ids;
        } else {
            return $user_ids[$pit_number];
        }
    }

    /**
     * @param $roomId
     * @param string $start
     * @param int $end
     * @param bool $withScores
     * @param int $page
     * @param int $limit
     * @return array
     * 获取
     */
    public static function getRoomUsersWithPage($roomId, $start = "+inf", $end = 0, $withScores = false, $page = 1, $limit = 3)
    {
        $roomUsersKey = 'room:users:' . $roomId;
        if (!app('redis')->exists($roomUsersKey)) {
            return [];
        }
        $options = ['withScores' => $withScores];
        $options['limit'] = [$page, $limit];
        $res = app('redis')->zRevRangeByScore($roomUsersKey, $start, $end, $options);
        if (!$res) {
            return [];
        }
        return $res;
    }

    /**
     * @param $userId
     * @return bool
     * 押宝 上锁
     */
    public static function addCastleLock($userId)
    {
        $key = 'castle:lock' . $userId;
        $uk = $userId;
        $res = app('redis')->set($key, $uk, 'ex', 2, 'nx');
        if (!$res) {
            return false;
        }
        return $uk;
    }

    /**
     * 押宝 解锁
     * @param $userId
     * @param string $uk
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public static function unLockCastleLock($userId, $uk = '')
    {
        $key = 'castle:lock' . $userId;
        $redis = app('redis');
        $cacheUk = $redis->get($key);
        if ($cacheUk && $cacheUk == $uk) {
            $redis->del($key);
        }
    }

    /**
     * @param $castleId
     * @param $userId
     * @param $time
     * @param int $sum_time
     * @param bool $type
     * @return int
     */
    public static function getCastleStakeUser($castleId, $userId, $time, $sum_time = 600, $type = false)
    {
        $key = 'castle:stake:user:' . $castleId;
        $keyDay = 'castle:stake:user:' . $time;
        // 每局押注的用户
        $redis = app('redis');
        if ($type) {
            if ($redis->exists($key)) {
                $data = $redis->lrange($key, 0, -1);
                $index = array_search($userId, $data);
                $redis->lrem($key, $index + 1, $userId);
            }
            if ($redis->exists($keyDay)) {
                $keyDay_data = $redis->lrange($keyDay, 0, -1);
                $keyDay_index = array_search($userId, $keyDay_data);
                $redis->lrem($key, $keyDay_index + 1, $userId);
            }
            return true;
        }
        if (!$redis->exists($key)) {
            $redis->lpush($key, $userId);
            $redis->expire($key, $sum_time + 60);
        } else {
            // 判断是否添加用了 未添加 就插入
            if (!in_array($userId, $redis->lrange($key, 0, -1) ?? [])) {
                $redis->lpush($key, $userId);
            }
        }
        // 每天押注的用户
        if (!$redis->exists($keyDay)) {
            $redis->lpush($keyDay, $userId);
            $redis->expire($keyDay, 86400 + 3600);
        } else {
            // 判断是否添加用了 未添加 就插入
            if (!in_array($userId, $redis->lrange($keyDay, 0, -1) ?? [])) {
                $redis->lpush($keyDay, $userId);
            }
        }
        return $redis->llen($key) ?? 0;
    }

    /**
     * @param $castleId
     * @param $userId
     * @param $count
     * @param string $type
     * @param int $sum_time
     * @return mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public static function getCastleStakeUserCount($castleId, $userId, $count, $type = 1, $sum_time = 600)
    {
        $key = 'castle:stake:user:count' . $castleId . '_' . $userId;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            $redis->set($key, $count);
            $redis->expire($key, $sum_time + 10);
            return $count;
        } else {
            if ($type == 1) {
                $redis->incrby($key, $count);
            } else {
                $redis->decrby($key, $count);
            }
            return $redis->get($key);
        }
    }


    /**
     * @param $castleId
     * @param $userId
     * @param $gift_info
     * @param $gift_id
     * @param $number
     * @param $lattice
     * @param int $type
     * @param int $sum_time
     * @return array
     * 用户信息  礼物信息只有第一次
     * @throws BasicException
     */
    public static function getCastleUser($castleId, $userId, $gift_info, $gift_id, $number, $lattice, $type = 1, $sum_time = 600)
    {
        $key = 'castle:gift:info:user:' . $castleId . ':' . $userId;
        // 获取传过来的数组 // 是否第一次过来 是的  进行 重置 count
        $redis = app('redis');
        if (!$redis->exists($key)) {
            // 存第一次
            if ($type != 1) {
                throw new BasicException(-1, '亲!已经减低了,不能再减了!');
            }
            collect($gift_info)->sortBy('lattice')->toArray();
            collect($gift_info)->sortByDesc('lattice')->toArray();
            array_multisort(array_column($gift_info, 'lattice'), SORT_DESC, $gift_info);
            $gift_info_new = [];
            foreach ($gift_info as $val) {
//                app("redis")->zadd($giveKey, [ $userId => $score ]);
                // 第一次全部重置
                $count = 0;
                if ($gift_id == $val['id']) {
                    $count = $number;
                    // 当前的用户押宝情况 当前的 押宝情况
                    $key2 = 'castle:gift:stake:user:' . $castleId . ':' . $gift_id;
                    if (!$redis->exists($key2)) {
                        $redis->zadd($key2, [$userId => $count]);
                        $redis->expire($key2, $sum_time + 30);
                    } else {
                        $redis->zadd($key2, [$userId => $count]);
                    }
                }
                $val['count'] = $count;
                // 不能使用有序集合
//                $redis->zadd($key,[json_encode($val)=>$val['id']]);
                $gift_info_new[$val['id']] = json_encode($val);
                // 礼物id
            }
            $redis->lpush($key, $gift_info_new);
            // 设置过期时间
            $redis->expire($key, $sum_time + 30);

        } else {
//            $values = Redis::zRange('myset', 0, -1)
            // 进行修改 拿出礼物 进行 改值的加数量就行 在进行修改集合数据
            $index = $lattice - 1;
            $data = $redis->lindex($key, $index);
            if ($data) {
                $data = json_decode($data, true);
                $key2 = 'castle:gift:stake:user:' . $castleId . ':' . $gift_id;
                if ($type == 1) {
                    $data['count'] = $data['count'] + $number;
                } else {
                    $data['count'] = $data['count'] - $number;
                }
                if ($data['count'] > 999) {
                    throw new BasicException(-1, '亲!最多增加999!');
                }
                if ($data['count'] < 0) {
                    throw new BasicException(-1, '亲!已经减低了,不能再减了!');
                }
                if (!$redis->exists($key2)) {
                    $redis->zadd($key2, [$userId => $data['count']]);
                    $redis->expire($key2, $sum_time + 30);
                } else {
                    if ($data['count'] == 0) {
                        $redis->zrem($key2, $userId);
                    } else {
                        $redis->zadd($key2, [$userId => $data['count']]);
                    }
                }
                $data = json_encode($data);
                $redis->lset($key, $index, $data);
            }
        }
        return $redis->lrange($key, 0, -1);
    }

    //获取正在使用的头像框
    public static function getHeadPicture($user_id)
    {
        return app('redis')->get(self::KEY_HEAD_PICTURE . $user_id);
    }

    //批量获取正在使用的头像框
    public static function getHeadPictures(array $user_ids = [])
    {
        if (empty($user_ids)) {
            return [];
        }
        $user_ids = array_unique($user_ids);
        $return = [];
        $redis_keys = [];
        foreach ($user_ids as $k => $v) {
            $redis_keys[] = self::KEY_HEAD_PICTURE . $v;
        }
        $head_pictures = app('redis')->mGet(...$redis_keys);
        foreach ($user_ids as $k => $v) {
            if (isset($head_pictures[$k]) && $head_pictures[$k] !== false) {
                $return[$v] = $head_pictures[$k];
            }
        }
        return $return;
    }

    //获取房间公屏状态 //1打开0关闭
    public static function getRoomChat($room_id)
    {
        $roomChatStatus = self::getRoomDetailByRoomId($room_id, 'screen_status');
        return $roomChatStatus == 1 ? 1 : 0;
        $is_close = app('redis')->sismember(self::KEY_ROOM_CHAT, $room_id);

        return $is_close == 1 ? 0 : 1;
    }

    //获取所有的白名单
    public static function whitelistList($user_id)
    {
        $key = 'user:message:' . $user_id;
        if (app('redis')->exists($key)) {
            return app('redis')->hgetall($key);
        }
        return [];
    }


    //删除白名单
    public static function delWhitelist($to_user_id, $user_id)
    {
        $key = 'user:message:' . $to_user_id;
        if (app('redis')->exists($key)) {
            app('redis')->hdel($key, $user_id);
        }
        return true;
    }

    //添加白名单
    public static function addWhitelist($to_user_id, $user_id)
    {
        $key = 'user:message:' . $to_user_id;
        app('redis')->hset($key, $user_id, 1);
        return true;
    }

    //添加好友关系
    public static function addFriend($user_id, $user_id_to)
    {
        $key = 'all:friends';
        if (!app('redis')->exists($key)) {
            self::initFriend();
        }
        $member = $user_id . '-' . $user_id_to;
        $member1 = $user_id_to . '-' . $user_id;
        app('redis')->sadd($key, $member);
        app('redis')->sadd($key, $member1);
    }


    //删除好友关系
    public static function delFriend($user_id, $user_id_to)
    {
        $key = 'all:friends';
        if (!app('redis')->exists($key)) {
            self::initFriend();
        }
        $member = $user_id . '-' . $user_id_to;
        $member1 = $user_id_to . '-' . $user_id;
        app('redis')->srem($key, $member);
        app('redis')->srem($key, $member1);
    }


    //查询好友关系(初始化,不存在key值时初始化)
    public static function initFriend()
    {
        $key = 'all:friends';
        $list = app('model_friend')->select('user_id', 'friend_id')->get()->toArray();

        //mysql的M方法
        $result = [];
        foreach ($list as $value) {
            $k = $value['user_id'] . '-' . $value['friend_id'];
            $result[$k] = 1;
        }
        $all_friend = array_keys($result);
        app('redis')->sadd($key, ...$all_friend);
    }


    /**
     * 根据room_id获取单个房间的人气值
     * @param int $room_id
     * @return int|number
     */
    public static function getPopularityByRoomId($room_id = 0)
    {
        $roomPopularity = self::getRoomPopularityS([$room_id]);;
        return $roomPopularity[$room_id] ?? 0;
        $roomPopularity = 0;
        $time = time();
        $pattern = 'popu:r:' . $room_id;  //非模糊匹配,准确搜索

        //查询符合条件的集合数组
        $keys_arr = app('redis')->zrangebyscore($pattern, $time, "+inf");
        if (!empty($keys_arr)) {
            $val_list = app('redis')->mget($keys_arr);  //查询不到返回false
            if ($val_list) {
                $roomPopularity = array_sum($val_list);
            }
        }

        return $roomPopularity;
    }

    /**
     * 2021/05/21重构 韩硕 根据chat_room_api新人气获取对应房间人气
     * 根据room_ids返回人气数组
     * @param array $room_ids
     * @return array
     */
    public static function getPopularityArr($room_ids = [])
    {
        return self::getRoomPopularityS($room_ids);
        $popularityArr = [];
        foreach ($room_ids as $val) {
            $popularityArr[$val] = self::getPopularityByRoomId($val);
        }
        return $popularityArr;
    }

    //获取房间人气
    public static function getRoomPopularityS($roomIds)
    {
        if (empty($roomIds)) {
            return [];
        }
        $redisKeys = [];
        foreach ($roomIds as $k => $v) {
            $roomIds[$k] = [
                'redisKey' => sprintf(RedisKeyEnum::ROOM_POPULARITY, $v),
                'key' => $v,
            ];
            $redisKeys[$k] = sprintf(RedisKeyEnum::ROOM_POPULARITY, $v);
        }
        $popularityArr = app('redis')->mGet($redisKeys);
        $return = [];
        foreach ($roomIds as $k => $v) {
            $return[$v['key']] = isset($popularityArr[$k]) ? $popularityArr[$k] : 0;
        }
        return $return;
    }

    public static function levelRoom($room_id, $uid)
    {
        $userInRoomKey = sprintf(RedisKeyEnum::USER_IN_ROOM, $uid);
        $roomUsersKey = sprintf(RedisKeyEnum::ROOM_USERS, $room_id);
        app('redis')->set($userInRoomKey, 0);
        app('redis')->zRem($roomUsersKey, $uid);
        return true;
    }


    public function getRoomsPopularity($ids)
    {
        $key = 'room:popularity:';
        $keys = array_map(function ($id) use ($key) {
            return $key . $id;
        }, $ids);
        $result = $keys ? array_map('intval', app('redis')->mget($keys)) : [];

        return array_combine($ids, $result);
    }

    //取当前类型 top1人气的房间(非隐藏)
    public function getTypeTopOnePopularity($type, $notValues = [])
    {
        $key = 'type:room:popularity:' . $type;
        $index = 0;
        $redis = app('redis');
        while (true) {
            $result = $redis->zRevRange($key, $index, $index);
            $value = array_pop($result);
            if (!$value) {
                break;
            }
            if (!in_array($value, $notValues)) {
                $roomDetail = self::getRoomDetailByRoomId($value);
                if (isset($roomDetail['state']) && empty($roomDetail['state'])) {   //状态为隐藏
                    $index++;
                    continue;
                } else {  //状态为显示,就是他了
                    break;
                }
            }
            $index++;
        }
        return $value ? (int)$value : $value;
    }


    /**
     * 离开房间清除相关key值
     * @param $room_id
     * @param $uid
     * @param int $type
     * @return bool
     */
    public static function clearPopularityByKey($room_id, $uid, $type = 1)
    {
        return self::levelRoom($room_id, $uid);
        if ($type == 1) {
            //加入房间的类别直接删除处理
            $sign_key = 'popu:join:k' . $room_id . $uid;
            $key = app('redis')->get($sign_key);

            if (isset($key) && !empty($key)) {
                $room_key = 'popu:r:' . $room_id;
                app('redis')->zrem($room_key, $key);
                app('redis')->del($key);
                app('redis')->del($sign_key);
                $roomPopularity = self::getPopularityByRoomId($room_id);

                //发送消息更新人气
                $push = new PushService(0, $room_id);
                $push->updatePopularity($roomPopularity);

                return $roomPopularity;
            }
        }
        $pattern = 'popu:p:' . $room_id . 't' . $type . 'u' . $uid . "*";
        $keys_arr = app('redis')->keys($pattern);
        $room_key = 'popu:r:' . $room_id;
        if (!empty($keys_arr)) {
            foreach ($keys_arr as $val) {
                app('redis')->zrem($room_key, $val);
                app('redis')->del($val);
            }
        }
        $roomPopularity = self::getPopularityByRoomId($room_id);

        //发送消息更新人气
        $push = new PushService(0, $room_id);
        $push->updatePopularity($roomPopularity);

        return $roomPopularity;
    }

    public static function getRoomPopularityType($type, $page = 1, $page_size = 100)
    {
        $start = ($page - 1) * $page_size;
        $end = $start + $page_size - 1;
        $allRoomKey = sprintf(RedisKeyEnum::TYPE_ROOM_POPULARITY, $type);
        $online_user = app('redis')->zrevrange($allRoomKey, $start, $end, 'WITHSCORES');
        return $online_user;
    }

    public static function getRoomPopularity($page = 1, $page_size = 100)
    {
        $start = ($page - 1) * $page_size;
        $end = $start + $page_size;
        $allRoomKey = RedisKeyEnum::ALL_ROOM_POPULARITY;
        $online_user = app('redis')->zrevrange($allRoomKey, $start, $end, 'WITHSCORES');
        return $online_user;
    }

    public static function getRoomPopularityByTypes($typeIds, $page = 1, $page_size = 100)
    {
        $start = ($page - 1) * $page_size;
        $end = $start + $page_size;
        $popularityRoom = [];
        foreach ($typeIds as $typeId) {
            $typeRoomKey = sprintf(RedisKeyEnum::TYPE_ROOM_POPULARITY, $typeId);;
            $online_user = app('redis')->zrevrange($typeRoomKey, 0, $end, 'WITHSCORES');
            $popularityRoom += $online_user;
        }
        if (empty($popularityRoom)) {
            return [];
        }
        arsort($popularityRoom);

        return array_slice(array_keys($popularityRoom), $start, $end);
    }

    /**
     * 2021/05/12重构 获取有序集合所有的房间人气
     * author Hso
     */
    public static function getRoomPopularityAll($min = '-inf', $max = '+inf')
    {
        $allRoomKey = RedisKeyEnum::ALL_ROOM_POPULARITY;
        $online_user = app('redis')->zrevrangebyscore($allRoomKey, $max, $min, 'WITHSCORES');
        return $online_user;
    }

    /**
     * 获取所有房间ID人气值数组
     * @return array
     */
    public static function getNewAllRoomPopuArr()
    {
        return self::getRoomPopularityAll();
        $popuListStr = app('redis')->get('popu:list');
        if (!empty($popuListStr)) {
            return json_decode($popuListStr, 1);
        }

        $pattern = 'popu:r:*';
        $keys_arr = app('redis')->keys($pattern);
        $room_ids = [];

        if ($keys_arr) {
            foreach ($keys_arr as $val) {
                $room_ids[] = substr($val, 7);
            }
        }
        $popularity_arr = self::getPopularityArr($room_ids);

        $popularity_arr = array_filter($popularity_arr);

        arsort($popularity_arr);

        app('redis')->set('popu:list', json_encode($popularity_arr));

        app('redis')->expire('popu:list', 600);

        return $popularity_arr;
    }

    /**
     * 减少房间人气 包含推送消息
     * @param $roomId int 房间id
     * @param $popularity int 减少的房间人数 为正数
     * @param string $key 唯一键,幂等防止重复减少
     * @return bool
     * author Hso
     */
    public static function decrRoomPopularity($roomId, $popularity, $key = '')
    {
        if (!empty($key)) {
            $miKey = sprintf(RedisKeyEnum::ROOM_POPULARITY_MI_DECR, $roomId);
            $isMem = app('redis')->sismember($miKey, $key);
            //已消费
            if ($isMem) {
                return true;
            }
        }
        $roomPopularityKey = sprintf(RedisKeyEnum::ROOM_POPULARITY, $roomId);
        $result = app('redis')->decrBy($roomPopularityKey, $popularity);
        $room_online_popularity = app('model_room_online_user')->where(['room_id' => $roomId])->sum('popularity');
        if ($result <= 0 || $result < $room_online_popularity) {
            app('redis')->set($roomPopularityKey, $room_online_popularity);
            $result = $room_online_popularity;
        }
        self::setRoomZsetPopularity($roomId, $result);
        if (!empty($key)) {
            $miKey = sprintf(RedisKeyEnum::ROOM_POPULARITY_MI_DECR, $roomId);
            app('redis')->sadd($miKey, $key);
            app('redis')->expire($miKey, self::ROOM_MAX_EXPIRE_TIME);
        }
        (new PushService(0, $roomId))->updatePopularity($result);
        return true;
    }

    //设置有序集合的房间人气
    public static function setRoomZsetPopularity($roomId, $popularity)
    {
        if ($popularity < 0) {
            return;
        }
        $allRoomKey = RedisKeyEnum::ALL_ROOM_POPULARITY;
        app('redis')->zAdd($allRoomKey, $popularity, $roomId);
        $roomType = self::getRoomDetailByRoomId($roomId, 'sys_type_id');
        $typeRoomKey = sprintf(RedisKeyEnum::TYPE_ROOM_POPULARITY, $roomType);
        app('redis')->zAdd($typeRoomKey, $popularity, $roomId);
    }

    //获取房间详情
    public static function getRoomDetailByRoomId($roomId, $member = false)
    {
        if ($roomId <= 0) {
            return [];
        }
        $key = sprintf(RedisKeyEnum::ROOM_INFO, $roomId);
        $redis = app('redis');
        if (!$redis->exists($key)) {
            $res = app('model_user_room')->getDetailById($roomId);
            if ($res) {
                $data = [
                    'union_type' => $res['union_type'], // 日返模式
                    'is_role' => $res['is_role'], // 是否官方
                    'sys_type_id' => $res['sys_type_id'], // 系统类型
                    'chatrooms' => $res['chatrooms'], // 融云房间
                    'ry_room' => $res['ry_room'],  // 融云房间
                    'wheat' => $res['wheat'], // 1.自由上麦  2.申请上麦
                    'nickname' => $res['nickname'], // 房主昵称
                    'head_picture' => $res['head_picture'], // 房主头像
                    'sex' => $res['sex'], // 房主性别
                    'seal_time' => $res['seal_time'], //封禁时间
                    'holder' => $res['holder'], // 房间主持用户id
                    'password' => $res['password'], // 房间密码
                    'room_name' => $res['room_name'], // 房间名称
                    'water_ratio' => $res['water_ratio'], // 房间流水百分比
                    'bg_picture' => $res['bg_picture'],     // 背景图
                    'screen_status' => $res['screen_status'], // 公屏状态
                    'cardiac_status' => $res['cardiac_status'], // 心动值状态
                    'sound_effect_id' => $res['sound_effect_id'], // 房间音效
                    'user_id' => $res['user_id'], // 房主id
                    'state' => $res['state'] ?? 1, // 房间隐藏状态
                    //以下后台修改均以清空缓存应该没问题
                    'show_ball_game' => $res['show_ball_game'], // 球球大作战
                    'id' => $res['id'], // id
                    'room_id' => $res['room_id'], // room_id
                    'cover_picture' => $res['cover_picture'], // 封面图
                    'playing' => $res['playing'], // 房间玩法
                    'label_id' => $res['label_id'], // 房间标签
                    'greeting' => $res['greeting'], // 房间欢迎语
                    'is_pretty' => $res['is_pretty'], // 是否靓号房1是0否
                    'is_boss_pit' => $res['is_boss_pit'], // 是否设置老板麦1是0否
                    'user_code' => $res['user_code'], // 房主的code

                    'label_name' => $res['label_name'], // 房间标签名称(可能标签更改后受影响)
                    'label_icon' => $res['label_icon'], // 房间标签名称(可能标签更改后受影响)
                    'step' => $res['step'], // 相亲房进行到第几部
                ];
                $redis->hMSet($key, $data);
            } else {
                $data = [];
            }
        } else {
            $data = $redis->hGetAll($key);
        }
        if ($member) {
            return $data[$member] ?? '';
        }
        return $data;
    }

    /**
     * 增加房间热度
     * @param $roomId
     * @param $popularity
     * @param int $type
     * @param int $expiredTime
     * @param int $sign
     * author Hso
     */
    public static function addRoomPopularity($roomId, $popularity, $type = 1, $expiredTime = 259200, $sign = 0)
    {
        $roomPopularityKey = sprintf(RedisKeyEnum::ROOM_POPULARITY, $roomId);
        //增加key value 的房间人气
        $incrRes = app('redis')->incrBy($roomPopularityKey, $popularity);
        //设置有序集合的房间人气
        self::setRoomZsetPopularity($roomId, $incrRes);
        //推送减少人气
        $key = uniqid() . mt_rand(10000, 99999);
        $data = [
            'room_id' => $roomId,
            'popularity' => $popularity,
            'type' => $type,
            'sign' => $sign,
            'key' => $key,
        ];
        if ($expiredTime) {
            $roomJob = (new GeneralRoomJob($data))->delay($expiredTime);
            dispatch($roomJob);
        }
        return $incrRes;
    }

    //-------------新的人气处理逻辑模块,废弃原有的两张表,废弃user_room和room_join的popularity字段,全部走redis string存储----------------

    /**
     * 增加人气记录
     * @param $room_id (房间编号)
     * @param $popularity (人气值)
     * @param int $type 1用户进入房间2送房间礼物3送背包礼物4周星榜人气5管理后台赠送人气6活动赠送7竞拍成功8点歌增加人气9单人房点击红心增加人气
     * @param int $expired_time (过期时间(1设置默认时间为7天,其余类型具体设置过期时间)默认3天
     * @param int $sign (可扩展用于各种类型,一期只用于销毁用户退出人气减少)
     * @return int|number   返回人气值
     */
    public static function setPopularityCache($room_id, $popularity, $type = 1, $expired_time = 259200, $sign = 0)
    {
        $roomPopularity = self:: addRoomPopularity($room_id, $popularity, $type, $expired_time, $sign);
        //发送消息
        (new PushService(0, $room_id))->updatePopularity($roomPopularity);

        return $roomPopularity;

        //开启事务存储room_id和popularity_value,暂不对异常处理
        app('redis')->multi();

        $time = time();

        $key = uniqid('popu:p:' . $room_id . 't' . $type . 'u' . $sign . 'd' . $time, true);

        $end_time = $time + $expired_time;

        if ($type == 1) {
            //用户加入房间涨人气的,记录一个roomid+uid绑定的key值
            $sign_key = 'popu:join:k' . $room_id . $sign;
            app('redis')->set($sign_key, $key);
        }

        app('redis')->setex($key, $expired_time, $popularity);

        $roomset_key = 'popu:r:' . $room_id;

        app('redis')->zadd($roomset_key, $end_time, $key);

        //记录日志
        //        $data = [
        //            'room_id'     => $room_id,
        //            'popularity'  => $popularity,
        //            'type'        => 1,
        //            'start_at'    => $time,
        //            'end_at'      => $time + $expired_time,
        //            'expire_time' => $expired_time,
        //            'sign'        => $sign,
        //        ];
        //
        //        $log_key = uniqid("popu:log:" . date('YmdHis', time()) . 'r' . $room_id . $type, true);
        //        app('redis')->set($log_key, json_encode($data));

        $status = app('redis')->exec();

        if (!$status) {
            app('redis')->discard();
        }   //异常回滚

        $roomPopularity = self::getPopularityByRoomId($room_id);

        //发送消息
        (new PushService(0, $room_id))->updatePopularity($roomPopularity);

        return $roomPopularity;
    }


    //设置用户在线
    public static function setOnline($room_id, $user_id)
    {
        $key = 'room:online:' . $room_id;
        if (!app('redis')->exists($key)) {
            $users = app('model_room_join')->getOnlineUserList($room_id);
            if (!$users) {
                app('redis')->sadd($key, ...$users);
            }
        }
        app('redis')->sadd($key, $user_id);
    }

    //设置用户有序集合上线
    public static function setOnlineZset($room_id, $user_id, $manager = 0, $room_info = array())
    {
        $key = "qp:room:users:" . $room_id;
        $isOk = true;
        if (!app('redis')->exists($key)) {
            $redisPreventKey = 'room:pr:lock:key:' . $room_id;//分布式锁防止并发读库，这里实现不是严格的锁，后续需要优化
            $lockSecond = 3;
            $uK = uniqid();
            if (app('redis')->setnx($redisPreventKey, $uK)) {
                app('redis')->expire($redisPreventKey, $lockSecond);
                $users = app('repo_room')->getOnlineUserAndManager($room_id, $room_info);
                if (!empty($users)) {
                    app('redis')->zadd($key, ...$users);
                    //过期时间600s
                    $expire = 600;
                    app('redis')->expire($key, $expire);
                }
                app('redis')->del($redisPreventKey);
                //                self::getDelete($redisPreventKey,$uK);
            } else {
                $isOk = false;
            }
        }
        app('redis')->zadd($key, $manager, $user_id);
    }

    /**
     * lua getAndDelete 分布式锁 不支持
     * @param $key
     * @param $identification
     * @return mixed
     * author Hso
     */
    public static function getDelete($key, $identification)
    {
        //        $script = <<< EOF
        //if redis.call("get", KEYS[1]) == ARGV[1] then
        //    return redis.call("del", KEYS[1])
        //else
        //    return 0
        //end
        //EOF;
        //        return app('redis')->eval($script, [$key, $identification], 1);
    }


    //设置用户下线
    public static function setOffline($room_id, $user_id)
    {
        $key = 'room:online:' . $room_id;
        $result = app('redis')->srem($key, $user_id);

        return $result > 0 ? 1 : 0;
    }

    //设置用户有序集合下线
    public static function setOfflineZset($room_id, $user_id)
    {
        $key = "qp:room:users:" . $room_id;
        $result = app('redis')->zrem($key, $user_id);

        return $result > 0 ? 1 : 0;
    }

    //获取用户在线状态
    public static function online($room_id, $user_id)
    {
        $key = 'room:online:' . $room_id;
        $result = app('redis')->sismember($key, $user_id);

        return $result ? 1 : 0;
    }

    //获取用户有序集合在线状态
    public static function onlineZset($room_id, $user_id)
    {
        $key = 'qp:room:users:' . $room_id;
        $result = app('redis')->zrank($key, $user_id);

        return isset($result) ? 1 : 0;
    }


    //获取麦位上的用户
    public static function getPit($room_id, $pit)
    {
        $user_id = app('redis')->hget('room:' . $room_id, 'pit' . $pit);

        return $user_id > 0 ? $user_id : 0;
    }

    //设置麦位上的用户
    public static function setPit($room_id, $pit, $user_id)
    {
        app('redis')->hset('room:' . $room_id, 'pit' . $pit, $user_id);
    }

    public static function getChatRooms($room_id)
    {
        $key = 'all:chatrooms';
        if (!app('redis')->exists($key)) {
            $list = app('model_user_room')->orderBy('id', 'asc')->select('id', 'chatrooms')->get();
            if ($list) {
                $list = $list->toArray();
                $all = array_column($list, 'chatrooms', 'id');
                app('redis')->hmset($key, $all);
            }
        }
        $chatrooms = app('redis')->hget($key, $room_id);

        return $chatrooms;
    }

    public static function getUserRegTime($user_id)
    {
        return self::getUserBaseInfo($user_id, 'register_time');
        $key = 'u:reg:time:' . $user_id;
        $register_time = app('redis')->get($key);
        if (!$register_time) {
            $register_time = app('model_user')->where(['user_id' => $user_id])->value('register_time');
            app('redis')->set($key, $register_time);
        }

        return $register_time;
    }

    //关闭|打开公屏 status:1打开0关闭
    public static function setRoomChat($room_id, $status = 1)
    {
        $key = 'room:chat:close';
        if ($status == 1) {
            app('redis')->srem($key, $room_id);
        } else {
            app('redis')->sadd($key, $room_id);
        }
    }

    public static function getUserMixer($room_id, $user_id)
    {
        $key = 'mixer:' . $room_id . ':' . $user_id;
        $id = app('redis')->get($key);

        return $id > 0 ? $id : 0;
    }

    public static function setUserMixer($room_id, $user_id, $id)
    {
        $key = 'mixer:' . $room_id . ':' . $user_id;
        $id = $id > 0 ? $id : 0;
        app('redis')->set($key, $id);
    }

    public static function getUserWithdrawTimes($user_id)
    {
        $key = 'u:w:t:' . $user_id;
        $times = app('redis')->get($key);
        if ($times <= 0) {
            $times = 0;
        }

        return $times;
    }

    public static function incUserWithdrawTimes($user_id)
    {
        $key = 'u:w:t:' . $user_id;
        app('redis')->incr($key);

        app('redis')->expire($key, todayLeftTime());
    }

    //type:1普通房引导2拍卖房引导3相亲房引导
    public static function checkGuide($user_id, $type = 1)
    {
        switch ($type) {
            case 2:
                $key = 'guide:user:auction';
                break;
            default:
                $key = 'guide:user';
        }
        if (!app('redis')->exists($key)) {
            $where['type'] = $type;
            $lists = app('model_room_guide')->where($where)->pluck('user_id');
            if ($lists->isEmpty()) {
                $lists = [0 => 0];
            }
            app('redis')->sadd($key, ...$lists);
        }

        return app('redis')->sismember($key, $user_id) ? 1 : 0;
    }

    public static function addGuideUser($user_id, $type = 1)
    {
        switch ($type) {
            case 2:
                $key = 'guide:user:auction';
                break;
            default:
                $key = 'guide:user';
        }
        app('redis')->sadd($key, $user_id);
    }

    public static function getRide($user_id)
    {
        $key = 'u:ride:' . $user_id;
        $result = app('redis')->get($key);
        if ($result) {
            return json_decode($result, true);
        }

        return null;
    }

    //个性装扮：进场特效
    public static function getJoinSpecial($user_id)
    {
        $key = 'u:join:special:' . $user_id;
        $result = app('redis')->get($key);
        if ($result) {
            return json_decode($result, true);
        }

        return null;
    }

    /**
     * 判断是否是房间管理员
     * @param $room_id
     * @param $user_id
     * @return
     */
    public static function checkRoomManager($room_id, $user_id)
    {
        $key = 'room:manager:' . $room_id;
        if (!app('redis')->exists($key)) {
            $list = app('model_room_manager')->where(['is_delete' => 0, 'room_id' => $room_id])->pluck('user_id');
            if (!$list->isEmpty()) {
                $list = $list->toArray();
                app('redis')->sadd($key, ...$list);
            }
        }

        return app('redis')->sismember($key, $user_id);
    }

    /**
     * 判断是否是房主
     * @param $room_id
     * @param $user_id
     * @return bool
     */
    public static function checkRoomOwner($room_id, $user_id)
    {
        $key = 'room:owner:' . $room_id;
        $owner = app('redis')->get($key);
        if (!$owner) {
            $owner = app('model_user_room')->where(['id' => $room_id])->value('user_id');
            app('redis')->set($key, $owner);
        }

        return $owner == $user_id;
    }

    /**
     * 获取用户系统设置
     * @param $user_id
     * @return bool
     */
    public static function getUserConfig($user_id)
    {
        $key = 'user:config:' . $user_id;
        if (app('redis')->exists($key)) {
            $result = app('redis')->get($key);

            return json_decode($result, true);
        } else {
            $result = app('model_user_config')->where('user_id', $user_id)->first();
            if (!empty($result)) {
                $result = $result->toArray();
                app('redis')->set($key, json_encode($result));
                return $result;
            }
        }

        return null;
    }

    public static function getAllAuctionRecord($auction_id)
    {
        $key = 'auction:' . $auction_id;
        if (!app('redis')->exists($key)) {
            $list = app('model_auction_record')->selectRaw('max(total_cost) as total_cost,user_id')->where('auction_id', $auction_id)->orderBy('total_cost', 'desc')->groupBy('user_id')->get();
            if (!$list->isEmpty()) {
                $data = array_column($list->toArray(), 'total_cost', 'user_id');
                app('redis')->zadd($key, $data);
            }
        }

        return app('redis')->zrevrange($key, 0, -1, "WITHSCORES");
    }

    public static function getLastAuctionRecord($auction_id)
    {
        $all_record = self::getAllAuctionRecord($auction_id);
        if (empty($all_record)) {
            return [];
        }
        return array_slice($all_record, 0, 1, true);
    }

    public static function addUserGiftWall($user_id, $gift_id)
    {
        $redis_key = 'u:g:w:' . $user_id;
        if (!app('redis')->exists($redis_key)) {
            self::initUserGiftWall($user_id);
        }

        return app('redis')->sadd($redis_key, $gift_id);
    }

    public static function initUserGiftWall($user_id)
    {
        $redis_key = 'u:g:w:' . $user_id;
        app('redis')->del($redis_key);
        $list = app('model_give_gift')->where('gift_user', $user_id)->selectRaw('sum(number) as total,gift_id,min(add_time) add_time')->groupBy('gift_id')->get();
        if ($list) {
            app('model_user_gift_wall')->where(['user_id' => $user_id])->delete();
            $data = [];
            foreach ($list as $key => $value) {
                app('redis')->sadd($redis_key, $value->gift_id);
                $data[] = [
                    'user_id' => $user_id,
                    'gift_id' => $value->gift_id,
                    'get_time' => $value->add_time,
                    'number' => $value->total,
                ];
            }
            app('model_user_gift_wall')->insert($data);
        } else {
            app('redis')->sadd($redis_key, 0);
        }
    }

    public function getCurrentWeekStarGift()
    {
        $weeks = date('YW');
        $key = 'weekstar:gift:' . $weeks;
        if (app('redis')->exists($key)) {
            return app('redis')->hgetall($key);
        } else {
            $result = M('WeekStar')->where(['weeks' => $weeks, 'deleted' => 0])->find();
            app('redis')->hmset($key, $result);
            app('redis')->expire($key, Helper::todayLeftTime());

            return $result;
        }
    }

    public function addWeekStarData($data)
    {
        $week_star_gift = $this->getCurrentWeekStarGift();
        if (!$week_star_gift) {
            return false;
        }
        $total = $data['total_price'];
        if ($total <= 0) {
            return false;
        }

        if (!in_array($data['gift_id'], [$week_star_gift['gift_id_1'], $week_star_gift['gift_id_2']])) {
            return false;
        }

        $room_id = $data['room_id'];
        $weeks = date('YW');
        if ($room_id > 0) {
            $key_room = 'weekstar:room:' . $weeks;
            app('redis')->zincrby($key_room, $total, $room_id);
        }
        $key_rich = 'weekstar:rich:' . $weeks;
        $key_charm = 'weekstar:charm:' . $weeks;
        app('redis')->zincrby($key_rich, $total, $data['user_id']);
        app('redis')->zincrby($key_charm, $total, $data['gift_user']);
    }

    public static function getAllNobilityUsers()
    {
        $key = 'nobility:users';
        $result = app('redis')->hgetall($key);
        if (!$result) {
            $nobility_users = app('model_user')->where('nobility', '>', 0)->where('deleted', 0)->pluck('nobility', 'user_id');

            if (!$nobility_users->isEmpty()) {
                $result = $nobility_users->toArray();
            } else {
                $result = [0 => 0];
            }
            app('redis')->hmset($key, $result);
        }

        return $result;
    }

    public static function getUserNobilityValue($user_id, $key)
    {
        $all_nobility_users = self::getAllNobilityUsers();
        $nobility_id = $all_nobility_users[$user_id] ?? 0;
        $nobility_config = app('model_nobility')->getNobilityConfigCache();

        return $nobility_config[$nobility_id][$key] ?? '';
    }

    /**
     * 最近来访用户集合
     * @param $user_id
     * @param $from
     * @param $to
     * @return
     */
    public static function getVisitUser($user_id, $from, $to)
    {
        $redis_key = 'visit:user:' . $user_id;
        if (!app('redis')->exists($redis_key)) {
            $list = app('model_user_visit')->visitListUser($user_id);
            if ($list) {
                $insert_data = [];
                foreach ($list as $key => $val) {
                    $insert_data[] = $val;
                    $insert_data[] = $key;
                }
                app('redis')->zadd($redis_key, ...$insert_data);
            }
        }

        return app('redis')->zrevrange($redis_key, $from, $to, 'WITHSCORES');
    }

    public static function addVisitUser($user_id, $visit_user = 0)
    {
        $redis_key = 'visit:user:' . $user_id;
        if (!app('redis')->exists($redis_key)) {
            $list = app('model_user_visit')->visitListUser($user_id);
            if ($list) {
                $insert_data = [];
                foreach ($list as $key => $val) {
                    $insert_data[] = $val;
                    $insert_data[] = $key;
                }
                app('redis')->zadd($redis_key, ...$insert_data);
            }
        }
        if ($visit_user > 0) {
            app('redis')->zadd($redis_key, Carbon::now()->timestamp, $visit_user);
        }
    }

    public static function fakeRoomIds($type_id = 0)
    {
        $room_ids = [];
        $list = app('redis')->get('fake:fake_recommend_list');
        if ($type_id > 0) {
            $list = empty($list) ? [] : json_decode($list, true);
            foreach ($list as $key => $item) {
                if ($item['sys_type_id'] > 0) {
                    if ($item['sys_type_id'] == $type_id) {
                        $room_ids[] = $item['room_id'];
                    }
                } else {
                    if ($item['type_id'] == $type_id) {
                        $room_ids[] = $item['room_id'];
                    }
                }
            }
        }

        return $room_ids;
    }

    /**
     * @param $content
     * @return int -1不存在缓存1通过2不通过
     */
    public function checkSensitive($content)
    {
        $key = 'sensitive';
        if (!app('redis')->exists($key)) {
            $list = app('model_sensitive_content')->where(['check_result' => 2])->pluck('content');
            app('redis')->sadd($key, ...$list);
            app('redis')->expire($key, 2592000);
        }
        if (app('redis')->sismember($key, $content)) {
            return 2;
        }
        $key1 = 'sensitive:not';
        if (!app('redis')->exists($key1)) {
            $list = app('model_sensitive_content')->whereIn('check_result', [0, 1])->pluck('content');
            app('redis')->sadd($key1, ...$list);
            app('redis')->expire($key1, 2592000);
            if (app('redis')->sismember($key1, $content)) {
                return 1;
            }
        }
        if (app('redis')->sismember($key1, $content)) {
            return 1;
        }

        return -1;
    }

    public function addSensitive($content)
    {
        app('redis')->sadd('sensitive', $content);
    }

    public function addSensitiveNot($content)
    {
        app('redis')->sadd('sensitive:not', $content);
    }

    /**
     * 收藏房间
     * @param $room_id
     * @param $user_id
     */
    public function addRoomFavorite($room_id, $user_id)
    {
        $key = sprintf(RedisKeyEnum::ROOM_FAVORITE, $room_id);
        $redis = app('redis');
        if ($redis->exists($key)) {
            $users = app('model_room_favorite')->getUserList($room_id);
            if (empty($users)) {
                $users = [];
            }
            $redis->sAdd($key, $users);
            $redis->expire($key, 2592000);
        }
        return $redis->sAdd($key, $user_id);
//        $key = 'room:fav:' . $room_id;
//        if (!app('redis')->exists($key)) {
//            $users = app('model_room_favorite')->getUserList($room_id);
//            if (!empty($users)) {
//                app('redis')->sadd($key, ...$users);
//            }
//            app('redis')->sadd($key, $user_id);
//            app('redis')->expire($key, 2592000);//有效时间30天
//        } else {
//            app('redis')->sadd($key, $user_id);
//        }
    }

    //设置用户爵位等级
    public static function setUserNobility($user_id, $nobility_id)
    {
        $key = 'nobility:users';
        app('redis')->hset($key, $user_id, $nobility_id);
    }

    //判断是否加入工会
    public static function checkGuildUser($user_id)
    {
        $key = 'guild:users';
        if (!app('redis')->exists($key)) {
            static::initSociatyUsers();
        }
        return app('redis')->sismember($key, $user_id);
    }

    public static function checkFriend($user_id, $user_id_to)
    {
        $key = 'all:friends';
        if (!app('redis')->exists($key)) {
            self::initFriend();
        }
        if (app('redis')->sismember($key, $user_id . '-' . $user_id_to)) {
            return true;
        } elseif (app('redis')->sismember($key, $user_id_to . '-' . $user_id)) {
            return true;
        }

        return false;
    }

    private static function initSociatyUsers()
    {
        $key = 'guild:users';
        app('redis')->del($key);
        $list = app('model_sc_sociaty_user')->select('user_id')->get();
        $userIds = [];
        foreach ($list as $v) {
            $userIds[] = $v->user_id;
        }
        if (!empty($userIds)) {
            app('redis')->sadd($key, ...$userIds);
        }
    }

    public static function getUserInRoom($user_id)
    {
        $key = sprintf(RedisKeyEnum::USER_IN_ROOM, $user_id);
        $result = app('redis')->get($key);
        return $result > 0 ? $result : 0;
    }

    // 获取用户信息
    public static function getUserBaseInfo($user_id, $field = '', $isBase = false)
    {
        $key = sprintf(RedisKeyEnum::USER_INFO, $user_id);
        if (!app('redis')->exists($key)) {
            $userInfo = app('repo_user_data')->getBaseUserInfo($user_id);
            if (!$userInfo) {
                return null;
            }
            $data = [
                'user_id' => $user_id,
                'role' => $userInfo['role'] ?? 1,    // 角色
                'register_time' => $userInfo['register_time'], // 注册时间
                'rank_id' => $userInfo['rank_id'] ?? 0, // vip登记
                'charm_id' => $userInfo['charm_id'] ?? 0, //
                'nobility' => $userInfo['nobility'] ?? 0, // 爵位id
                'user_code' => $userInfo['user_code'] ?? '',
                'sex' => $userInfo['sex'] ?? 0, // 性别
                'head_picture' => $userInfo['head_picture'] ?? '', // 头像
                'nickname' => $userInfo['nickname'] ?? '', // 昵称
                'ry_token' => $userInfo['ry_token'] ?? '', // 融云token
                'channel_stage_id' => $userInfo['channel_stage_id'] ?? '', //渠道分期idvip登记
                'birthday' => $userInfo['birthday'], //生日
                'signature' => $userInfo['signature'] ?? '', //签名
                'streamer_level' => $userInfo['streamer_level'] ?? 0, //主播等级
            ];
            app('redis')->hmset($key, $data);
        } else {
            $data = app('redis')->hgetall($key);
        }

        $isNew = 0;
        $register_time = $data['register_time'] ?? 0;
        if ($register_time >= (time() - RoomEnum::USER_NEW_TIME)) { // 天
            $isNew = 1;
        }
        $data['user_is_new'] = $isNew;
        $data['recharge_icon'] = self::getUserRechargeIcon($user_id);

        if (!$isBase) {
            $rank_id = $data['rank_id'] ?? 0;
            $nobility_id = $data['nobility'] ?? 0;
            $charm_id = $data['charm_id'] ?? 0;
            $grade_info = app('model_grade_config')->getGradeConfig($rank_id);
            $charm_info = app('model_charm_config')->getCharmConfig($charm_id);
            $nobility_info = app('model_nobility')->getNobilityInfo($nobility_id);

            $data['rank_icon'] = $grade_info['head_picture'] ?? '';
            $data['rank_name'] = $grade_info['grade'] ?? '';
            $data['moods'] = $nobility_info['moods'] ?? 0;
            $data['nobility_id'] = $nobility_info['id'] ?? '';
            $data['nobility_name'] = $nobility_info['name'] ?? '';
            $data['nobility_icon'] = $nobility_info['head_picture'] ?? '';
            $data['charm_icon'] = $charm_info['head_picture'] ?? '';
            $data['charm_name'] = $charm_info['grade'] ?? '';
            // 实时用户正在使用的头像框
            $data['dress_picture'] = RedisService::getHeadPicture($user_id);//头像框
        }
        if ($field) {
            return $data[$field] ?? '';
        }
        return $data;
    }

    // 获取用户信息
    public static function batchGetUserBaseInfo($userIds, $isBase = false)
    {

        if (count($userIds) > 50) {
            throw new BasicException(-1, '查询人数过多');
        }
        app('redis')->del(sprintf(RedisKeyEnum::USER_INFO, 617));
        app('redis')->del(sprintf(RedisKeyEnum::USER_INFO, 618));
        $userDataList = app('redis')->pipeline(function ($pipe) use ($userIds) {
            foreach ($userIds as $userId) {
                $pipe->hgetall(sprintf(RedisKeyEnum::USER_INFO, $userId));
            }
        });
        $userDataList = array_filter($userDataList);
        //获取在缓存中的等级 贵族ID
        $cacheUserIds = array_column($userDataList, 'user_id');
        $cacheRankIds = array_filter(array_unique(array_column($userDataList, 'rank_id')));
        $cacheNobilityIds = array_filter(array_unique(array_column($userDataList, 'nobility')));

        $userDataList = array_column($userDataList, null, 'user_id');

        //查询缺失的userIds
        $unCachedUserIds = array_diff($userIds, array_keys($userDataList));

        if (count($unCachedUserIds) > 0) {
            $unCachedUserDataList = app('repo_user_data')->batchGetBaseUserInfo($unCachedUserIds);
            if (!empty($unCachedUserDataList)) {
                $unCacheDataList = [];
                foreach ($unCachedUserDataList as $unCacheUser) {
                    $unCacheDataList[$unCacheUser['user_id']] = [
                        'user_id' => $unCacheUser['user_id'],
                        'role' => $unCacheUser['role'] ?? 1,    // 角色
                        'register_time' => $unCacheUser['register_time'], // 注册时间
                        'rank_id' => $unCacheUser['rank_id'] ?? 0, // vip登记
                        'nobility' => $unCacheUser['nobility'] ?? 0, // 爵位id
                        'user_code' => $unCacheUser['user_code'] ?? '',
                        'sex' => $unCacheUser['sex'] ?? 0, // 性别
                        'head_picture' => $unCacheUser['head_picture'] ?? '', // 头像
                        'nickname' => $unCacheUser['nickname'] ?? '', // 昵称
                        'rank_icon' => $unCacheUser['rank_icon'] ?? '', //
                        'nobility_icon' => $unCacheUser['nobility_icon'] ?? '', //
                        'rank_name' => $unCacheUser['rank_name'] ?? '', //
                        'channel_stage_id' => $unCacheUser['channel_stage_id'] ?? '', //渠道分期id
                    ];
                }

                app('redis')->pipeline(function ($pipe) use ($unCacheDataList) {
                    foreach ($unCacheDataList as $unCacheUserId => $unCacheValue) {
                        unset($unCacheValue['rank_name']);
                        unset($unCacheValue['rank_icon']);
                        unset($unCacheValue['nobility_icon']);
                        $pipe->hmset(sprintf(RedisKeyEnum::USER_INFO, $unCacheUserId), $unCacheValue);
                    }
                });

                $userDataList = array_merge($userDataList, $unCacheDataList);
            }
        }
        $isNew = 0;
        if (!$isBase) {
            //获取最新的rank和nobility 刷新缓存的rank_icon nobility
            $gradeList = app('model_grade_config')->batchGetGradeList($cacheRankIds);
            $nobilityList = app('model_nobility')->batchGetNobilityList($cacheNobilityIds);
            if (!empty($gradeList)) {
                $gradeListWithId = $gradeList->KeyBy('id');
            }

            if (!empty($nobilityList)) {
                $nobilityListWithId = $nobilityList->KeyBy('id');
            }

            foreach ($userDataList as &$userValue) {
                if (in_array($userValue['user_id'], $cacheUserIds)) {
                    if (isset($gradeListWithId[$userValue['rank_id']])) {
                        $userValue['rank_icon'] = $gradeListWithId[$userValue['rank_id']]['head_picture'] ?? '';
                        $userValue['rank_name'] = $gradeListWithId[$userValue['rank_id']]['grade'] ?? '';
                    } else {
                        $userValue['rank_icon'] = '';
                        $userValue['rank_name'] = '';
                    }
                    if (isset($nobilityListWithId[$userValue['nobility']])) {
                        $userValue['nobility_icon'] = $nobilityListWithId[$userValue['nobility']]['head_picture'] ?? '';
                        $userValue['nobility_name'] = $nobilityListWithId[$userValue['nobility']]['name'] ?? '';
                    } else {
                        $userValue['nobility_icon'] = '';
                        $userValue['nobility_name'] = '';
                    }
                }

                $register_time = $data['register_time'] ?? 0;
                if ($register_time >= (time() - RoomEnum::USER_NEW_TIME)) { // 天
                    $isNew = 1;
                }
                $userValue['user_is_new'] = $isNew;
            }
        }
        return $userDataList;
    }

    // 删除用户信息缓存
    public static function clearUserInfo($user_id)
    {
        $key = sprintf(RedisKeyEnum::USER_INFO, $user_id);
        app('redis')->del($key);
    }

    // 获取房间内用户人数
    public static function getRoomUserNum($room_id, $min = 0, $max = 3000000000)
    {
        $roomUsersKey = sprintf(RedisKeyEnum::ROOM_USERS, $room_id);
        $redis = app('redis');
        $count = $redis->zCount($roomUsersKey, $min, $max);
        return $count > 0 ? $count : 0;
    }

    //删除爵位用户
    public static function delUserNobility($user_id)
    {
        $key = RedisKeyEnum::NOBILITY_USERS;
        app('redis')->hdel($key, $user_id);
    }

    public static function getRoomPopularityByType($type_id)
    {
        $key = sprintf(RedisKeyEnum::TYPE_ROOM_POPULARITY, $type_id);
        $list = app('redis')->zrevrangebyscore($key, "+inf", 1, 'WITHSCORES');
        return $list;
    }

    public static function getRoomType($typeId)
    {
        $key = 'room:type:name';
        $typeToName = app('redis')->get($key);
        $typeToName = empty($typeToName) ? [] : json_decode($typeToName, true);
        if (empty($typeToName)) {
            $typeToName = app('model_room_type')->get();
            $typeToName = empty($typeToName) ? [] : $typeToName->toArray();
            $typeToName = indexToAssoc($typeToName, 'id');
            app('redis')->setex($key, 86400, json_encode($typeToName));
        }
        return isset($typeToName[$typeId]) ? $typeToName[$typeId]['room_type_name'] : '';
    }

    public static function getRoomSoundEffect($soundEffectId = 0)
    {
        $redis = app('redis');
        $key = 'room:sound:effect';
        $soundEffect = $redis->get($key);
        $soundEffect = empty($soundEffect) ? [] : json_decode($soundEffect, true);
        if (empty($soundEffect)) {
            $soundEffect = app('model_room_sound_effect')->get();
            $soundEffect = empty($soundEffect) ? [] : $soundEffect->toArray();
            $soundEffect = indexToAssoc($soundEffect, 'id');
            $redis->setex($key, 86400, json_encode($soundEffect));
        }
        if (empty($soundEffectId)) {
            return $soundEffect;
        } else {
            if (isset($soundEffect[$soundEffectId])) {
                $soundEffect[$soundEffectId]['config'] = json_decode($soundEffect[$soundEffectId]['config'], true);
                return $soundEffect[$soundEffectId];
            } else {
                return new \ArrayObject();
            }
        }
    }

    //推送文本，用户信息及标签获取
    public static function getUserChatLabel($userId, $roomId = 0, $userInfo = [], $roomInfo = [])
    {
        $userInfo = $userInfo ? $userInfo : self::getUserBaseInfo($userId);
        if ($roomId) {
            $roomInfo = $roomInfo ? $roomInfo : self::getRoomDetailByRoomId($roomId);
        } else {
            $roomInfo = [];
        }
        // 额外信息
        $isRoomOwn = $isRoomManger = $isRoomHolder = $isOffice = 0;
        if ($roomInfo && $userId == $roomInfo['user_id']) { // 房间管理
            $isRoomOwn = 1;
        }
        if ($roomInfo && self::checkRoomManager($roomId, $userId)) { // 管理
            $isRoomManger = 1;
        }
        //主持
        if ($roomInfo && $userId == $roomInfo['holder']) {
            $isRoomHolder = 1;
        }
        $user_role = $userInfo['role'] ?? 0;
        if ($user_role == 2) {
            $isOffice = 1;
        }
        $user_special = self::special($userId);
        return [
            'is_room_own' => $isRoomOwn,
            'is_room_manger' => $isRoomManger,
            'is_room_holder' => $isRoomHolder,
            'is_office' => $isOffice,
            'nickname' => $userInfo['nickname'] ?? '',
            'avatar' => $userInfo['head_picture'] ?? '',
            'head_picture' => $userInfo['head_picture'] ?? '',
            'rank_icon' => $userInfo['rank_icon'] ?? '',
            'charm_icon' => $userInfo['charm_icon'] ?? '',
            'special' => $user_special,
            'nobility_icon' => $userInfo['nobility_icon'] ?? '',
            'user_is_new' => $userInfo['user_is_new'] ?? 0,
            'user_id' => $userInfo['user_id'] ?? 0,
            'user_code' => $userInfo['user_code'] ?? 0,
            'rank_name' => $userInfo['rank_name'] ?? '',
        ];
    }

    //推送文本，用户信息及标签获取
    public static function batchGetUserChatLabel($userIds)
    {
        $userDataList = self::batchGetUserBaseInfo($userIds);
//        $userInfo = $userInfo ? $userInfo : self::getUserBaseInfo($userId);
//        if ($roomId) {
//            $roomInfo = $roomInfo ? $roomInfo : self::getRoomDetailByRoomId($roomId);
//        } else {
//            $roomInfo = [];
//        }
//        // 额外信息
//        $isRoomOwn = $isRoomManger = $isRoomHolder = $isOffice = 0;
//        if ($roomInfo && $userId == $roomInfo['user_id']) { // 房间管理
//            $isRoomOwn = 1;
//        }
//        if ($roomInfo && self::checkRoomManager($roomId, $userId)) { // 管理
//            $isRoomManger = 1;
//        }
//        //主持
//        if ($roomInfo && $userId == $roomInfo['holder']) {
//            $isRoomHolder = 1;
//        }

        $userChatLabelList = [];
        foreach ($userDataList as $userId => &$user) {
            $user['is_room_own'] = 0;
            $user['is_room_manger'] = 0;
            $user['is_room_holder'] = 0;
            $user['is_office'] = $user['role'] == 2 ? 1 : 0;
            $user['avatar'] = $user['head_picture'] ?? '';
            $user['special'] = self::special($userId);
        }

        return $userDataList;
    }

    public static function special($userId)
    {
        $redis = app('redis');
        $data = $redis->mget(
            RedisKeyEnum::USER_NICKNAME . $userId,
            RedisKeyEnum::USER_NICKNAME_SPECIAL . $userId,
            RedisKeyEnum::USER_RIDE . $userId,
            RedisKeyEnum::USER_JOIN_SPECIAL . $userId,
            RedisKeyEnum::USER_CHAT_BUBBLE . $userId,
            RedisKeyEnum::USER_ROOM_CHAT_BUBBLE . $userId,
            RedisKeyEnum::USER_SOUND_WAVE . $userId,
            RedisKeyEnum::USER_GLOBAL_BROADCAST . $userId,
            RedisKeyEnum::USER_HP . $userId,
            RedisKeyEnum::USER_CARD_FRAME . $userId
        );
        $nicknameWidget = json_decode($data[0], true);
        $nickname_special = json_decode($data[1], true);
        $ride = json_decode($data[2], true);
        $join = json_decode($data[3], true);
        $chat = json_decode($data[4], true);
        $chatroom = json_decode($data[5], true);
        $wave = json_decode($data[6], true);
        $broadcast = json_decode($data[7], true);
        $avatar = $data[8] ?? '';
        $card_frame = json_decode($data[9], true);

        $chatroomMaterial = '';
        if (empty($chat['special'])) {
            $chatroomMaterial = $chatroom['special'] ?? ''; //公屏
        }


        return [
            'avatar' => [
                'material' => $avatar ?: '',
            ],
            'nickname' => [
                'material' => $nicknameWidget['special'] ?? ($nicknameWidget['picture'] ?? ''),
            ],
            'nickname_special' => [
                'material' => $nickname_special['special'] ?? '',
            ],
            'ride' => [
                'material' => $ride['special'] ?? '',
                'show_type' => $ride['show_type'] ?? 1,
            ],
            'join' => [
                'color' => $join['special'] ?? '',
                'material' => $join['picture'] ?? '',
                'show_type' => $join['show_type'] ?? 1,
            ],
            'chat' => [
                'material' => $chat['special'] ?? '',
            ],
            'chatroom' => [
                'material' => $chatroomMaterial
            ],
            'wave' => [
                'material' => $wave['special'] ?? ''
            ],
            'broadcast' => [
                'material' => $broadcast['special'] ?? ''
            ],
            'card_frame' => [
                'material' => $card_frame['special'] ?? ''
            ],
        ];
    }

    public static function setRoomUserContribution($room_id, $user_id, $user_id_to, $total_price)
    {
        if ($room_id > 0 && $user_id > 0 && $total_price > 0 && $user_id != $user_id_to) {
            $user_in_room_id = RedisService::getUserInRoom($user_id);
            if ($user_in_room_id != $room_id) {
                return;
            }
            $key = sprintf(RedisKeyEnum::ROOM_USER_CONTRIBUTION, $room_id, $user_id);
            if (!app('redis')->exists($key)) {
                $contribution = app('model_give_gift')->where(['user_id' => $user_id, 'room_id' => $room_id])->where('user_id', '<>', 'gift_user')->where('add_time', '>=', 1627747200)->sum('total_price');

                $room_user_contribution = $contribution > 0 ? intval($contribution) : 0;
                app('redis')->setex($key, 86400, $room_user_contribution);
            } else {
                $room_user_contribution = app('redis')->incrby($key, $total_price);
            }

            $roomVipUsersKey = sprintf(RedisKeyEnum::ROOM_VIP_USERS, $room_id);
            $nobility_id = RedisService::getUserBaseInfo($user_id, 'nobility');

            $room_contribution_config = RedisService::getRoomContributionConfig();
            $base_contribution = $room_contribution_config[0]['value'] ?? 0;
            if ($base_contribution > 0 && $room_user_contribution >= $base_contribution || $nobility_id > 0) {
                $score = $nobility_id + $room_user_contribution * 100;
                app('redis')->zadd($roomVipUsersKey, $score, $user_id);
            }
        }
    }

    public static function getRoomUserContribution($room_id, $user_id)
    {
        $key = sprintf(RedisKeyEnum::ROOM_USER_CONTRIBUTION, $room_id, $user_id);
        if (!app('redis')->exists($key)) {
            $contribution = app('model_give_gift')->where(['user_id' => $user_id, 'room_id' => $room_id])->where('user_id', '<>', 'gift_user')->where('add_time', '>=', 1627747200)->sum('total_price');
            $contribution = $contribution > 0 ? intval($contribution) : 0;
            app('redis')->setex($key, 86400, $contribution);
        } else {
            $contribution = app('redis')->get($key);
            $contribution = $contribution > 0 ? $contribution : 0;
        }
        return $contribution;
    }

    // 获取房间贡献度等级配置
    public static function getRoomContributionConfig()
    {
        $key = RedisKeyEnum::ROOM_CONTRIBUTION_CONFIG;
        if (!app('redis')->exists($key)) {
            $config = app('model_room_contribution_config')->orderBy('value', 'asc')->get()->toArray();
            if (empty($config)) {
                return [];
            }
            app('redis')->set($key, json_encode($config));
        } else {
            $config = app('redis')->get($key);
            $config = json_decode($config, true);
        }
        return $config;
    }

    static public function getUserGetGiftWall($userId)
    {
        $redisKey = 'user:gift:get:wall:' . $userId;
        $redis = app('redis');
        if (!$redis->exists($redisKey)) {
            self::createUserGetGiftWall($userId);
        }
        return $redis->sMembers($redisKey);
    }

    static public function getUserGiveGiftWall($userId)
    {
        $redisKey = 'user:gift:give:wall:' . $userId;
        $redis = app('redis');
        if (!$redis->exists($redisKey)) {
            self::createUserGiveGiftWall($userId);
        }
        return $redis->sMembers($redisKey);
    }


    static public function addUserGiveGiftWall($userId, $giftId)
    {
        if (empty($giftId)) {
            return false;
        }
        $redis = app('redis');
        $redisKey = 'user:gift:give:wall:' . $userId;
        if (!is_array($giftId)) {
            $giftIdArr[] = $giftId;
        } else {
            $giftIdArr = $giftId;
        }
        if (!$redis->exists($redisKey)) {
            return self::createUserGiveGiftWall($userId); // 合并数据并创建.
        }
        return $redis->sAdd($redisKey, ...$giftIdArr);
    }

    static public function addUserGetGiftWall($userId, $giftId)
    {
        if (empty($giftId)) {
            return false;
        }
        $redis = app('redis');
        $redisKey = 'user:gift:get:wall:' . $userId;
        if (!is_array($giftId)) {
            $giftIdArr[] = $giftId;
        } else {
            $giftIdArr = $giftId;
        }
        if (!$redis->exists($redisKey)) {
            $result = $redis->sAdd($redisKey, ...$giftIdArr);
            self::createUserGetGiftWall($userId, $giftIdArr); // 更新
        } else {
            $result = $redis->sAdd($redisKey, ...$giftIdArr);
        }
        return $result;
    }

    private static function createUserGiveGiftWall($userId)
    {
        $redisKey = 'user:gift:give:wall:' . $userId;
        $redis = app('redis');
        $redis->del($redisKey);
        $list = app('model_give_gift')
            ->where('gift_user', $userId)
            ->where('type', 2)
            ->selectRaw('sum(number) as total,gift_id,min(add_time) add_time')
            ->groupBy('gift_id')
            ->get()
            ->toArray();
        $list = array_column($list, 'gift_id');
        if (empty($list)) {
            $list = [0];
        }
        return $redis->sadd($redisKey, ...$list);
    }

    private static function createUserGetGiftWall($userId, $addData = [])
    {
        $redisKey = 'user:gift:get:wall:' . $userId;
        $redis = app('redis');
        $redis->del($redisKey);
        $list = app('model_give_gift')
            ->where('gift_user', $userId)
            ->where('type', 1)
            ->selectRaw('sum(number) as total,gift_id,min(add_time) add_time')
            ->groupBy('gift_id')
            ->get()
            ->toArray();
        $list = array_column($list, 'gift_id');
        if (!empty($addData)) {
            $list = array_merge($list, $addData);
        }
        if (empty($list)) {
            $list = [0];
        }
        return $redis->sadd($redisKey, ...$list);
    }

    //获取我要上公屏活动是否开启开奖中
    public static function checkActivityIsOpening($activityId)
    {
        $limitKey = 'screen:opening:' . $activityId;
        $lockKey = uniqid() . mt_rand(1000, 9999);
        return app('redis')->set($limitKey, $lockKey, 'ex', 3, 'nx');
    }

    //删除正在开启键
    public static function deleteActivityOpeningKey($activityId, $lockKey)
    {
        $limitKey = 'screen:opening:' . $activityId;
        if (app('redis')->get($limitKey) == $lockKey) {
            app('redis')->del($limitKey);
        }
    }

    //获取用户参与列表
    public static function getJoinScreenActivityList($activityId)
    {
        $redis = app('redis');
        $key = RedisKeyEnum::SCREEN_ACTIVITY_JOIN_LIST . $activityId;
        if (!$redis->exists($key)) {
            self::initScreenActivityJoinList($activityId);
        }
        return $redis->hgetAll($key);
    }

    //初始化我要上公屏参与详情
    public static function initScreenActivityJoinList($activityId)
    {
        $redis = app('redis');
        $key = RedisKeyEnum::SCREEN_ACTIVITY_JOIN_LIST . $activityId;
        $list = app('model_screen_lottery_num')->where('activity_id', $activityId)->get(['user_id', 'lottery_num']);
        $list = empty($list) ? [] : $list->toArray();
        $redisList = [-1 => 0];
        foreach ($list as $k => $v) {
            $redisList[$v['user_id']] = $v['lottery_num'];
        }
        $redis->hMSet($key, $redisList);
        return $redisList;
    }

    public static function getUserConnectExpToday($uk, $relationId, $isFirst = false)
    {
        $today = date('Ymd');
        $key = RedisKeyEnum::USER_CONNECT_EXP . $today . ':' . $uk;
        if (!app('redis')->exists($key)) {
            if ($isFirst) {
                $exp = 0;
            } else {
//                //不取了,可能导致12点数据库爆炸 应该取两个人赠送的总金币数的
                $exp = app('model_connect_intimacy_log')->where([
                    ["relation_id", "=", $relationId],
                    ["change_type", "=", 2],
                    ["created_at", ">=", date('Y-m-d')]
                ])->sum('intimacy');
                $exp = empty($exp) ? 0 : $exp * 100;
            }
            app('redis')->setex($key, 86400, (int)$exp);
        } else {
            $exp = app('redis')->get($key);
        }
        return $exp;
    }

    //设置亲密关系hset
    public static function getUserHasRelation($uk)
    {

        $redis = app('redis');
        $key = RedisKeyEnum::RELATION_ALL;
        if (!$redis->exists($key)) {
            self::initUserRelation();
        }
        return $redis->hGet($key, $uk);
    }

    public static function initUserRelation()
    {
        $redis = app('redis');
        $key = RedisKeyEnum::RELATION_ALL;
        $relation = app('model_connect_relation')->where([
            'status' => 1,
        ])->get(['unique_key', 'type']);
        $relation = empty($relation) ? [] : $relation->toArray();
        $res = [
            -1 => -1
        ];
        foreach ($relation as $k => $v) {
            $res[$v['unique_key']] = $v['type'];
        }
        $redis->hMSet($key, $res);
    }


    //删除用户关系
    public static function deleteUserRelation($uk, $type)
    {
        $redis = app('redis');
        $key = RedisKeyEnum::RELATION_ALL;
        $redis->hDel($key, $uk);
        $zSetKey = RedisKeyEnum::RELATION_RANK . $type;
        $redis->zRem($key, $zSetKey);
    }

    //设置CP亲密关系有序集合
    public static function addRelationIntimacy($uk, $intimacy = 0, $type = 1)
    {
        $redis = app('redis');
        $zSetKey = RedisKeyEnum::RELATION_RANK . $type;
        if (!$redis->exists($zSetKey)) {
            self::initRelationIntimacy($type);
            return true;
        }
        $redis->zInCrBy($zSetKey, (int)$intimacy, $uk);
    }

    public static function addRelationExpToday($uk, $relationId, $exp)
    {
        $today = date('Ymd');
        $key = RedisKeyEnum::USER_CONNECT_EXP . $today . ':' . $uk;
        if (!app('redis')->exists($key)) {
            $exp = app('model_connect_intimacy_log')->where([
                ["relation_id", "=", $relationId],
                ["change_type", "=", 2],
                ["created_at", ">=", date('Y-m-d')]
            ])->sum('intimacy');
            $exp = empty($exp) ? 0 : $exp * 100;
            app('redis')->setex($key, 86400, (int)$exp);
        } else {
            $exp = app('redis')->incrby($key, (int)$exp);
        }
        return $exp;
    }

    //初始化CP亲密关系有序集合
    static public function initRelationIntimacy($type)
    {
        $zSetKey = RedisKeyEnum::RELATION_RANK . $type;
        $relation = app('model_connect_relation')->where([
            'status' => 1,
            'type' => $type,
        ])->get(['unique_key', 'intimacy']);
        $relation = empty($relation) ? [] : $relation->toArray();
        $addData = [-1, -1];
        foreach ($relation as $v) {
            $score = empty($v['intimacy']) ? 0 : (int)($v['intimacy'] * 100);
            array_push($addData, $score);
            array_push($addData, $v['unique_key']);
        }
        $redis = app('redis');
        $redis->zAdd($zSetKey, ...$addData);
        $redis->expire($zSetKey, 864000);
    }

    //判断用户是否增加接收礼物到背包的操作
    public static function LockUserIsGetGiftToBag($userId)
    {
        $redisKey = RedisKeyEnum::USER_ACCEPTING_GIFT_TO_BAG . $userId;
        $uk = uniqidReal();
        app('redis')->set($redisKey, $uk, 'ex', 2, 'nx');
        return $uk;
    }

    //解锁用户是否增加接收礼物到背包的操作
    public static function unLockUserIsGetGiftToBag($userId, $uk)
    {
        $redisKey = RedisKeyEnum::USER_ACCEPTING_GIFT_TO_BAG . $userId;
        $redis = app('redis');
        $cacheUk = $redis->get($redisKey);
        if ($cacheUk && $cacheUk == $uk) {
            $redis->del($redisKey);
        }
    }

    static public function addUserGiftWallExp($userId, $exp)
    {
        $redis = app('redis');
        $userGiftWallExpKey = "user:gift:wall:exp:" . $userId;
        return $redis->incrBy($userGiftWallExpKey, $exp);
    }

    //增加用户cp经验值上限bug
    public static function addConnectRelationExpLock($relationId)
    {
        $redis = app('redis');
        $userGiftWallExpKey = "cp:connect:add:exp:lock:" . $relationId;
        $uniKey = uniqidReal();
        $lock = $redis->set($userGiftWallExpKey, $uniKey, 'ex', 3, 'nx');
        if (!$lock) {
            return false;
        } else {
            return $uniKey;
        }
    }

    //删除人脉亲密关系锁
    public static function deleteConnectRelationExpLock($relationId, $uniKey)
    {
        $redis = app('redis');
        $userGiftWallExpKey = "cp:connect:add:exp:lock:" . $relationId;
        $lock = $redis->get($userGiftWallExpKey);
        if ($lock == $uniKey) {
            $redis->del($userGiftWallExpKey);
        }
    }

    // 设置房间魅力值
    public static function setRoomCardiac($roomId, $pit_number, $rough_number)
    {
        $redis = app('redis');
        $key = 'room:cardiac:' . $roomId;
        $redis->zInCrBy($key, $rough_number, $pit_number);
    }

    // 设置房间总魅力值
    public static function setRoomCharm($roomId, $charm)
    {
        $redis = app('redis');
        $key = 'room:charm:' . $roomId;
        return $redis->incrBy($key, $charm);
    }

    // 获取房间总魅力值
    public static function getRoomCharm($roomId)
    {
        $redis = app('redis');
        $key = 'room:charm:' . $roomId;
        return $redis->get($key);
    }

    public static function createDynamicBrowseUser(int $id)
    {
        $expire = 300;
        $key = "dynamic:browse:" . $id;
        $redis = app('redis');
        $users = DynamicBrowseRepository::getInstance()
            ->all(['is_delete' => 0])
            ->pluck('user_id');
        if (empty($users)) {
            $users = [0];
        }

        $res = $redis->sadd($key, $users);
        $redis->expire($key, $expire);
        return $res;
    }

    public static function addDynamicBrowseUser(int $id, int $userId)
    {
        $key = "dynamic:browse:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicBrowseUser($id);
        }
        return $redis->sadd($key, [$userId]);
    }

    public function removeDynamicBrowseUser(int $id, int $userId)
    {
        $key = "dynamic:browse:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicBrowseUser($id);
        }
        return $redis->srem($id, $userId);
    }

    public static function createDynamicLikeUser(int $id)
    {
        $expire = 300;
        $key = "dynamic:like:" . $id;
        $redis = app('redis');
        $users = DynamicLikeRepository::getInstance()
            ->all(['is_delete' => 0])
            ->pluck('user_id');
        if (empty($users)) {
            $users = [0];
        }
        $res = $redis->sadd($key, $users);
        $redis->expire($key, $expire);
        return $res;
    }

    public static function addDynamicLikeUser(int $id, int $userId)
    {
        $key = "dynamic:like:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicLikeUser($id);
        }
        return $redis->sadd($key, [$userId]);
    }

    public static function removeDynamicLikeUser(int $id, int $userId)
    {
        $key = "dynamic:like:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicLikeUser($id);
        }
        return $redis->srem($key, $userId);
    }

    public static function createDynamicLikeReplyUser(int $id)
    {
        $expire = 300;
        $key = "dynamic:like:reply:" . $id;
        $redis = app('redis');
        $users = DynamicLikeRepository::getInstance()
            ->all(['is_delete' => 0])
            ->pluck('user_id');
        if (empty($users)) {
            $users = [0];
        }
        $res = $redis->sadd($key, $users);
        $redis->expire($key, $expire);
        return $res;
    }

    public static function addDynamicLikeReplyUser(int $id, int $userId)
    {
        $key = "dynamic:like:reply:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicLikeReplyUser($id);
        }
        return $redis->sadd($key, [$userId]);
    }

    public static function removeDynamicLikeReplyUser(int $id, int $userId)
    {
        $key = "dynamic:like:reply:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicLikeReplyUser($id);
        }
        return $redis->srem($key, $userId);
    }

    public static function createDynamicFollowUser(int $id)
    {
        $expire = 300;
        $key = "dynamic:follow:" . $id;
        $redis = app('redis');
        $users = DynamicFollowRepository::getInstance()
            ->all(['is_delete' => 0])
            ->pluck('user_id');
        if (empty($users)) {
            $users = [0];
        }
        $res = $redis->sadd($key, $users);
        $redis->expire($key, $expire);
        return $res;
    }

    public static function addDynamicFollowUser(int $id, int $userId)
    {
        $key = "dynamic:follow:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicLikeUser($id);
        }
        return $redis->sadd($key, [$userId]);
    }

    public static function removeDynamicFollowUser(int $id, int $userId)
    {
        $key = "dynamic:follow:" . $id;
        $redis = app('redis');
        if (!$redis->exists($key)) {
            self::createDynamicLikeUser($id);
        }
        return $redis->srem($key, $userId);
    }

    public static function getRoomCardiac($roomId)
    {
        $redis = app('redis');
        $key = 'room:cardiac:' . $roomId;
        $result = $redis->zrevrange($key, 0, -1, 'WITHSCORES');
        $data = [];
        foreach ($result as $pit => $rough_number) {
            if ($pit <= 0) {
                continue;
            }
            $data[] = [
                'room_id' => $roomId,
                'pit_number' => $pit,
                'rough_number' => $rough_number
            ];
        }
        return $data;
    }

    public static function sandDynamicLock(int $userId)
    {
        $key = 'dynamic:send:lock:' . $userId;
        $redis = app('redis');
        $value = randCode(6);
        $res = $redis->set($key, $value, 'ex', 60, 'nx');
        if (!$res) {
            return false;
        }
        return $value;
    }

    public static function clearDynamicLock(int $userId, $value)
    {
        $key = 'dynamic:send:lock:' . $userId;
        $redis = app('redis');
        $get = $redis->get($key);
        if ($get == $value) {
            return $redis->del($key);
        }
        return false;
    }

    // 设置用户刷新动态
    static public function setUserRefreshDynamic(int $userId, array $dynamicIds)
    {
        if (empty($dynamicIds)) {
            return [];
        }
        $expire = 86400;
        $key = 'user:refresh:dynamic:' . $userId;
        $redis = app('redis');
        $res = $redis->sadd($key, $dynamicIds);
        $redis->expire($key, $expire);
        return $res;
    }

    // 获取用户刷新动态
    static public function getUserRefreshDynamic(int $userId)
    {
        $key = 'user:refresh:dynamic:' . $userId;
        $redis = app('redis');
        $ids = $redis->smembers($key);
        if (empty($ids)) {
            return [];
        }
        return $ids;
    }

    // 清楚用户刷新动态
    static public function clearUserRefreshDynamic(int $userId)
    {
        $key = 'user:refresh:dynamic:' . $userId;
        $redis = app('redis');
        return $redis->del($key);
    }

    static public function userJoinGroupLock(int $userId)
    {
        $key = 'group:join:lock:' . $userId;
        $redis = app('redis');
        return $redis->set($key, $userId, 'ex', 2, 'nx');
    }

    static public function sendGroupBulletinLock(int $groupId)
    {
        $key = 'group:bulletin:send:lock:' . $groupId;
        $redis = app('redis');
        return $redis->set($key, $groupId, 'ex', 2, 'nx');
    }


    //推送文本，用户信息及标签获取
    public static function getUserGroupChatLabel($userId, $groupId = 0): array
    {
        if ($userId == 0) {
            return [];
        }
        $userInfo = self::getUserBaseInfo($userId);
        // 设置为群昵称
        $group = GroupMemberRepository::getInstance()->one(["group_id" => $groupId, 'user_id' => $userId]);
        if ($group && !empty($group->nickname)) {
            $userInfo['nickname'] = $group->nickname;
            $userInfo['group_role'] = $group->role;
        }

        $user_role = $userInfo['role'] ?? 0;
        if ($user_role == 2) {
            $isOffice = 1;
        }
        $user_special = self::special($userId);
        return [
            'is_office' => $isOffice ?? 0,
            'nickname' => $userInfo['nickname'] ?? '',
            'avatar' => $userInfo['head_picture'] ?? '',
            'head_picture' => $userInfo['head_picture'] ?? '',
            'rank_icon' => $userInfo['rank_icon'] ?? '',
            'special' => $user_special,
            'nobility_icon' => $userInfo['nobility_icon'] ?? '',
            'user_is_new' => $userInfo['user_is_new'] ?? 0,
            'user_id' => $userInfo['user_id'] ?? 0,
            'user_code' => $userInfo['user_code'] ?? 0,
            'rank_name' => $userInfo['rank_name'] ?? '',
            "group_role" => $userInfo['group_role'] ?? 0,
        ];
    }

    public static function getRoomPopularityRank($start = '-inf', $stop = '+inf')
    {
        $allRoomKey = RedisKeyEnum::ALL_ROOM_POPULARITY;
        return app('redis')->zrevrange($allRoomKey, $start, $stop);
    }

    // 设置群名审核状态
    static public function setGroupNameAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_NAME_AUDIT_FIELD, true);
    }

    // 删除群名审核状态
    static public function unsetGroupNameAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_NAME_AUDIT_FIELD, false);
    }

    // 获取群名审核状态
    static public function getGroupNameAuditStatus(int $groupId)
    {
        return self::getGroupAuditStatus($groupId, RedisKeyEnum::GROUP_NAME_AUDIT_FIELD);
    }

    // 设置群头像审核状态
    static public function setGroupAvatarAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_AVATAR_AUDIT_FIELD, true);
    }

    // 删除群头像审核状态
    static public function unsetGroupAvatarAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_AVATAR_AUDIT_FIELD, false);
    }

    // 获取群头像审核状态
    static public function getGroupAvatarAuditStatus(int $groupId)
    {
        return self::getGroupAuditStatus($groupId, RedisKeyEnum::GROUP_AVATAR_AUDIT_FIELD);
    }

    // 设置群封面审核状态
    static public function setGroupCoverAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_COVER_AUDIT_FIELD, true);
    }

    // 删除群封面审核状态
    static public function unsetGroupCoverAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_COVER_AUDIT_FIELD, false);
    }

    // 获取群封面审核状态
    static public function getGroupCoverAuditStatus(int $groupId)
    {
        return self::getGroupAuditStatus($groupId, RedisKeyEnum::GROUP_COVER_AUDIT_FIELD);
    }

    // 设置群简介审核状态
    static public function setGroupIntroductionAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_INTRODUCTION_AUDIT_FIELD, true);
    }

    // 删除群简介审核状态
    static public function unsetGroupIntroductionAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_INTRODUCTION_AUDIT_FIELD, false);
    }

    // 获取群简介审核状态
    static public function getGroupIntroductionAuditStatus(int $groupId)
    {
        return self::getGroupAuditStatus($groupId, RedisKeyEnum::GROUP_INTRODUCTION_AUDIT_FIELD);
    }

    // 设置群公告审核状态
    static public function setGroupBulletinAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_BULLETIN_AUDIT_FIELD, true);
    }

    // 删除群公告审核状态
    static public function unsetGroupBulletinAuditStatus(int $groupId)
    {
        return self::setGroupAuditStatus($groupId, RedisKeyEnum::GROUP_BULLETIN_AUDIT_FIELD, false);
    }

    // 获取群公告审核状态
    static public function getGroupBulletinAuditStatus(int $groupId)
    {
        return self::getGroupAuditStatus($groupId, RedisKeyEnum::GROUP_BULLETIN_AUDIT_FIELD);
    }

    // 批量设置群审核状态
    static public function batchSetGroupAuditStatus(int $groupId, array $kvMap)
    {
        $key = RedisKeyEnum::getInstance()->getGroupAuditStatusKey($groupId);
        $result = app('redis')->hmset($key, $kvMap);
        // 刷新过期时间
        app('redis')->expire($key, 2 * 86400); // 2天
        return $result;
    }

    // 设置群审核状态
    static public function setGroupAuditStatus(int $groupId, string $field, bool $value)
    {
        return self::batchSetGroupAuditStatus($groupId, [$field => $value]);
    }

    // 获取群审核状态
    static public function getGroupAuditStatus(int $groupId, string $field = "")
    {
        $key = RedisKeyEnum::getInstance()->getGroupAuditStatusKey($groupId);
        if (empty($field)) {
            return app('redis')->hgetall($key);
        }
        return app('redis')->hget($key, $field);
    }

    // 清空群审核状态
    static public function clearGroupAuditStatus(int $groupId)
    {
        $key = RedisKeyEnum::getInstance()->getGroupAuditStatusKey($groupId);
        return app('redis')->del($key);
    }

    static public function generateStreamerDayTaskLock($value = 1)
    {
        $key = "streamer:task:day:generate:lock";
        return app("redis")->set($key, $value, 'EX', 10, 'NX');
    }

    static public function generateStreamerWeekTaskLock($value = 1)
    {
        $key = "streamer:task:week:generate:lock";
        return app("redis")->set($key, $value, 'EX', 10, 'NX');
    }

    static public function addLotteryTurntableBalanceLock(int $userId): string
    {
        $key = "game:lottery-turntable:balance:user:lock:" . $userId;
        $redis = app("redis");
        $value = time() . mt_rand(1000, 9999);
        $res = $redis->setnx($key, $value);
        if (!$res) {
            return "";
        }
        return $value;
    }

    static public function removeLotteryTurntableBalanceLock(int $userId, $value)
    {
        $key = "game:lottery-turntable:balance:user:lock:" . $userId;
        $redis = app("redis");
        $v = $redis->get($key);
        if ($v != $value) {
            return 0;
        }
        return $redis->del($key);
    }


    static public function addStreamerStatChatUser(int $userId, int $chatUserId)
    {
        // $key = "streamer:chat-user:stat:" .
        $date = date("Y-m-d");
        $key = "streamer:$userId:chat-user:stat:$date";
        $redis = app("redis");
        if ($redis->exists($key)) {
            return $redis->sadd($key, [$chatUserId]);
        }
        $res = $redis->sadd($key, [$chatUserId]);
        $redis->expire($key, 86400 * 2);
        return $res;
    }

    static public function removeStreamerStatChatUser(int $userId, int $chatUserId)
    {
        $date = date("Y-m-d");
        $key = "streamer:$userId:chat-user:stat:$date";
        $redis = app("redis");
        return $redis->srem($key, $chatUserId);
    }

    static public function createOnlineVoiceUserIds(int $count, int $expire = 300)
    {
        $key = "online:voice:users";
        $userIds = UserRepository::getInstance()->getOnlineVoiceUsers();
        if ($userIds->isEmpty()) {
            $userIds = [0];
        } else {
            $userIds = $userIds->toArray();
        }

        $redis = app("redis");
        $redis->sadd($key, $userIds);
        $redis->expire($key, $expire);

        shuffle($userIds);
        return array_slice($userIds, -$count);
    }

    static public function getOnlineVoiceUserIds(int $count = 20)
    {
        $key = "online:voice:users";
        $redis = app("redis");
        if (!$redis->exists($key)) {
            return self::createOnlineVoiceUserIds($count);
        }
        return $redis->srandmember($key, $count);
    }

    static public function setWechatAccessToken(string $appId, string $token, int $second)
    {
        $key = "wechat:access_token:" . $appId;
        return app("redis")->setex($key, $second, $token);
    }

    static public function getWechatAccessToken(string $appId)
    {
        $key = "wechat:access_token:" . $appId;
        return app("redis")->get($key);
    }

    public static function checkIsAllowChat($userId)
    {
        $key = 'guild:allow:chat:user';
        return app("redis")->sIsMember($key, $userId);
    }

    static public function setUserCurrentCityLock(int $userId, int $expire = 3600)
    {
        $key = "user:current-city:lock:" . $userId;
        return app('redis')->set($key, time(), 'ex', $expire, 'nx');
    }

    static public function refreshUserCurrentCityLock(int $userId, int $expire = 60)
    {
        $key = "user:current-city:lock:" . $userId;
        return app('redis')->expire($key, $expire);
    }

    static public function getUserHomeRecommendStreamer(int $userId)
    {
        $key = "user:home:recommend-streamer:" . $userId;
        $redis = app("redis");
        return $redis->smembers($key);
    }

    static public function setUserHomeRecommendStreamer(int $userId, array $userIds)
    {
        if (!empty($userIds)) {
            $key = "user:home:recommend-streamer:" . $userId;
            $redis = app("redis");
            $redis->sadd($key, $userIds);
            $redis->expire($key, 24 * 60 * 60);
        }
    }

    static public function clearUserHomeRecommendStreamer(int $userId)
    {
        $key = "user:home:recommend-streamer:" . $userId;
        return app("redis")->del($key);
    }

    static public function setAccompanyUserCache($gameId, $conditions, $sort, $page, $perPage, $data, $expire = 3 * 60)
    {
        $key = "home:accompany:users:game-$gameId-status-sort-$sort-page-$page-perPage-$perPage-condition-$conditions";
        return app("redis")->set($key, json_encode($data), 'ex', $expire);
    }

    static public function getAccompanyUserCache($gameId, $condition, $sort, $page, $perPage)
    {
//        $key = "home:accompany:users:game-$gameId-status-$status-sex-$sex-region-$region-sort-$sort-advantage-$advantage-service-$service-page-$page-perPage-$perPage";

        $conditions = json_encode($condition, true);
        $key = "home:accompany:users:game-$gameId-status-sort-$sort-page-$page-perPage-$perPage-condition-$conditions";
        $res = app("redis")->get($key);
        if (empty($res)) {
            return [];
        }
        return json_decode($res, true);
    }

    public static function checkConnection($userId)
    {
        $key = RedisKeyEnum::CONNECTION_GENDER_USER . $userId;
        $owner = app('redis')->get($key);
        $status = 0;
        if (!$owner) {
            $status = 1;
            app('redis')->set($key, 1);
        }
        return $status;
    }

    public static function getRecommendInConnection($userId)
    {
        $key = 'anchor:connection:in:user' . $userId;
        $data = app('redis')->get($key);
        app('redis')->del($key);
        return $data;
    }

    static public function setAccompanyLevelUserCache($data)
    {
        $key = "home:accompany:users:level";
        return app("redis")->set($key, json_encode($data));
    }

    static public function getAccompanyLevelUserCache()
    {
        $key = "home:accompany:users:level";
        $res = app("redis")->get($key);
        if (empty($res)) {
            return [];
        }
        return json_decode($res, true);
    }

    static public function setNx($key, $value, $expired = -1)
    {
        $redis = app("redis");
        $res = $redis->setnx($key, $value);
        if ($res && $expired > 0) {
            $redis->expire($key, $expired);
        }
        return $res;
    }

    static public function del($key)
    {
        $redis = app("redis");
        return $redis->del($key);
    }

    public function checkAccompany($user_id)
    {
        $key = 'u:accompany:coupon' . $user_id;
        $owner = app('redis')->set($key, 1, 'ex', 5, 'nx');;

        return $owner;
    }


    public static function getBroadcastSpecial($userId)
    {
        $broadcast = json_decode(app("redis")->get(RedisKeyEnum::USER_GLOBAL_BROADCAST . $userId), true);
        return $broadcast['special'] ?? '';
    }

    // $index -1:全部 0:id 1:op_type 2:冠名名称 3:礼物id
    public static function getUserTitleNow($userId, $index = 2)
    {
        $redis = app('redis');
        $redisKeyNow = 'titleGift:' . $userId . ':now';
        $getValue = $redis->get($redisKeyNow);
        if (empty($getValue)) {
            return '';
        }
        $ary = explode('_', $getValue);
        if ($index == -1) {
            return $ary;
        }
        return $ary[$index] ?? '';
    }

    //特定的礼物存redis
    public static function getGiftInfo($giftId, $key = '', $redis = '')
    {
        if (empty($redis)) {
            $redis = app('redis');
        }
        if (empty($key)) {
            $key = 'titleGift:gift_' . $giftId;
        }
        if ($redis->exists($key)) {
            return json_decode($redis->get($key), true) ?? [];
        } else {
            $field = "id, name, price, picture, special, cardiac, category_id, op_type, type, frame_id,prize_pool_group_id,room_sys_type, 0 as is_chart_let, size, pk_score";
            $info = app('model_gift')->where('id', $giftId)->selectRaw($field)->first()->toArray();
            $redis->set($key, json_encode($info, JSON_UNESCAPED_UNICODE));
            return $info;
        }
    }

    /**获取用户的充值标志
     * @param $userId
     * @param bool $user_is_new 是否新用户
     * @return string
     */
    public static function getUserRechargeIcon($userId, $user_is_new = true)
    {
        $new_user_recharge_key = sprintf(UserEnum::NEW_USER_RECHARGE, $userId);
        if (app('redis')->exists($new_user_recharge_key)) {
            return 'https://biluo-cs.oss-cn-hangzhou.aliyuncs.com/manage_api/rech_new_u.png';
        }
        return '';
    }

    /**
     * @param $user_id
     * @return string
     */
    public static function setGuildUser($user_id)
    {
        $key = 'guild:users';
        $key_new = 'guild:users:new';
        if (app('redis')->exists($key)) {
            if (app('redis')->sismember($key, $user_id)) {
                // 查找公会name
                if (app('redis')->hexists($key_new, $user_id)) {
                    return json_decode(app('redis')->hget($key_new, $user_id))->sociaty_name ?: '';
                }
                $sc_id = app('model_sc_sociaty_user')->where('user_id', $user_id)->value('sociaty_id') ?? 0;
                $sc_info = app('model_sc_sociaty')->where('id', $sc_id)->first();
                app('redis')->hset($key_new, $user_id, json_encode($sc_info));
                return $sc_info['sociaty_name'];
            }
            return '';
        }
        return '';
    }

    //获取碎片组合
    public static function getDrawFragmentGroup($prefix_key, $model, $giftTemplateModel)
    {
        $key = $prefix_key. 'fragment:group';
        $redis = app('redis')->connection('game');
        if ($redis->exists($key)) {
            $data = json_decode($redis->get($key), true);
        } else {
            $data = $model->get()->toArray();
            foreach ($data as &$group) {
                if ($group['is_all']) {
                    $group['gift_list'] = [];
                } else {
                    $group['gift_list'] = $giftTemplateModel
                        ->from($giftTemplateModel->getTable(). ' as b')
                        ->join(app('model_gift')->getTable().' as a', 'a.id', '=', 'b.gift_id')
                        ->selectRaw('a.id,a.title as name,a.price,a.img as picture,b.id as gift_template_id')
                        ->whereIn('b.id', $group['gift_template_ids'])
                        ->get()->toArray();
                }
            }
            $redis->set($key, json_encode($data, JSON_UNESCAPED_UNICODE));
        }
        return $data;
    }

}
